Connection string. Cannot implicitly convert 'String' to 'System.Data.SqlClient.SqlConnection' - sql-server

I'm getting that error in title.
For my
cmd.Connection = Conn;
I have this
public string Conn = connection.getConnection();
I'm using a windows application, how do I fix this?
Here is my complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Room : Form
{
public SqlDataReader re;
public string Conn = connection.getConnection();
public Room()
{
InitializeComponent();
}
private void Room_Load(object sender, EventArgs e)
{
..
..
..
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "insertToRoom";
cmd.Parameters.AddWithValue("#room_name", textBox1);
cmd.Parameters.AddWithValue("#room_rate", textBox2);
cmd.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please fill in all the textbox.", "Wrong Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

Try this way. First get the connection string from web.conf or app.conf and then create a sqlconnection to assign to sqlcommand.
var connectionString =
ConfigurationManager.ConnectionStrings["NameofConstringFromWebconfig"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection =new SqlConnection(connectionString);

Related

Save excel file in database using c#

I have an excel file. Now I need to save data of excel file in database. What is the simplest way to do that using c# with simple example? Thank in advance
This will do what you want.
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_path\\Import_List.xls;Extended Properties=Excel 8.0;");
ExcelConnection.Open();
string expr = "SELECT * FROM [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection);
OleDbDataReader objDR = null;
SqlConnection SQLconn = new SqlConnection();
string ConnString = "Data Source=Your_Database_Name;Initial Catalog=Table_Name;Trusted_Connection=True;";
SQLconn.ConnectionString = ConnString;
SQLconn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn))
{
bulkCopy.DestinationTableName = "tblTest";
try
{
objDR = objCmdSelect.ExecuteReader();
bulkCopy.WriteToServer(objDR);
ExcelConnection.Close();
//objDR.Close()
SQLconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
To copy from a SQL Server table to an Excel file, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Or, with a 'Where' clause, you can have more control of the output.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

How to import Excel file data into database?

I've created a form where the manager can import an Excel file to DataGridView but I'm having trouble saving it to the database.
Reason: So when the manager imports the rota Excel file to DataGridView I want the other users to see it in a different form.
My form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace Login
{
public partial class EmployeeRota : Form
{
string con = "Data Source=dqq5ndqef2.database.windows.net;Initial Catalog=Login;Integrated Security=False;User ID=richardjacobs97;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EmployeeRota()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string PathCpnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathCpnn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
myDataAdapter.Update(dt);
}
private void EmployeeRota_Load(object sender, EventArgs e)
{
string connectionString = con;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Rota (Id, Name, Date) Values (#Id, #Name, #Date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
int i = 0;
i = dataGridView1.RowCount - 1;
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
}
Database: Database pic
Form: Form pic
Any suggestions why I get this error?
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
You are receiving that error because the Load function runs when the page is first opened. You should move this into a separate functions so that it can be called at select times, maybe from a button click. This is prior to any data source being applied to the
DataGridView. You need to add the following to make sure there are rows in the table.
i = dataGridView1.RowCount - 1;
if(i<0) // Meaning that the row count was 0
{
return;
}
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);

Need to click on a button in iFrame page

I am trying to click on "btnPunch". This button is located in an iFrame. I am unable to make this work. I have used the Selenium IDE to record this button being clicked and created a DLL that also runs this process in NUnit without a problem. Any help would be appreciated after three months of working on this.
Thank you
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using NUnit.Framework;
using Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
namespace TimeClockEntry
{
public partial class PNow : Form
{
IWebDriver driver = new InternetExplorerDriver();
//driver = new InternetExplorerDriver();
//private ISelenium selenium;
//private StringBuilder verificationErrors;
//public void SetupTest()
//{
// selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://ew23.ultipro.com/");
// selenium.Start();
// verificationErrors = new StringBuilder();
//}
int linkcount = 0;
string userName;
string passWord;
public PNow()
{
InitializeComponent();
webBrowser1.Navigate("https://ew23.ultipro.com/login.aspx");
}
private void PNow_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
userName = Properties.Settings.Default.userName;
passWord = Properties.Settings.Default.passWord;
}
private void PNow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
welcome f1 = new welcome();
f1.ShowDialog();
this.Close();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", userName);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", passWord);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
// driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
this.Close();
}
}
}
}
You can try this also:-
if (linkcount == 3)
{
WebElement frameSwitch = driver.findElement(By.xpath("Xpath of iframe")); //Frame Xpath
driver.switchTo().frame(frameSwitch);
driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
driver.switchTo().defaultContent();
this.Close();
}
Try this.
if (linkcount == 3)
{
//get back to basic html source.
driver.SwitchTo().DefaultContent();
//switch to new frame
driver.SwitchTo().Frame("<FRAME NAME OR ID>");
driver.FindElement(By.Id("btnPunch")).Click();
}

how to create sqlite database in wpf?

I am new to windows desktop application development.Will you please suggest me how to create a SQLite database in windows presentation foundation(wpf)?
You need to do 2 things:
Add the SQLite dll to your application references
Write a class that builds the Db.
for example:
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Database
{
public class DbCreator
{
SQLiteConnection dbConnection;
SQLiteCommand command;
string sqlCommand;
string dbPath = System.Environment.CurrentDirectory + "\\DB";
string dbFilePath;
public void createDbFile()
{
if (!string.IsNullOrEmpty(dbPath) && !Directory.Exists(dbPath))
Directory.CreateDirectory(dbPath);
dbFilePath = dbPath + "\\yourDb.db";
if (!System.IO.File.Exists(dbFilePath))
{
SQLiteConnection.CreateFile(dbFilePath);
}
}
public string createDbConnection()
{
string strCon = string.Format("Data Source={0};", dbFilePath);
dbConnection = new SQLiteConnection(strCon);
dbConnection.Open();
command = dbConnection.CreateCommand();
return strCon;
}
public void createTables()
{
if (!checkIfExist("MY_TABLE"))
{
sqlCommand = "CREATE TABLE MY_TBALE(idnt_test INTEGER PRIMARY KEY AUTOINCREMENT,code_test_type INTEGER";
executeQuery(sqlCommand);
}
}
public bool checkIfExist(string tableName)
{
command.CommandText = "SELECT name FROM sqlite_master WHERE name='" + tableName + "'";
var result = command.ExecuteScalar();
return result != null && result.ToString() == tableName ? true : false;
}
public void executeQuery(string sqlCommand)
{
SQLiteCommand triggerCommand = dbConnection.CreateCommand();
triggerCommand.CommandText = sqlCommand;
triggerCommand.ExecuteNonQuery();
}
public bool checkIfTableContainsData(string tableName)
{
command.CommandText = "SELECT count(*) FROM " + tableName;
var result = command.ExecuteScalar();
return Convert.ToInt32(result) > 0 ? true : false;
}
public void fillTable()
{
if (!checkIfTableContainsData("MY_TABLE"))
{
sqlCommand = "insert into MY_TABLE (code_test_type) values (999)";
executeQuery(sqlCommand);
}
}
}
}
Good luck!
1.using System.Data;
2.using System.Data.SQLite;
DataTable tb = new DataTable();
string connection = #"Data Source=C:\Folder\SampleDB.db;Version=3;New=False;Compress=True;";
SQLiteConnection sqlite_conn = new SQLiteConnection(connection);
string stringQuery = "Select * from Student";
sqlite_conn.Open();
var SqliteCmd = new SQLiteCommand();
SqliteCmd = sqlite_conn.CreateCommand();
SqliteCmd.CommandText = stringQuery;
SQLiteDataAdapter da = new SQLiteDataAdapter(SqliteCmd);
DataSet ds = new DataSet();
da.Fill(tb);

Failing to connect to SQL Server from C#

I am trying to import excel file into SQL Server 2005 in C#, but I', getting an error.
Here's my code:
namespace excel
{
public partial class Csharp_Excel : Form
{
public Csharp_Excel()
{
InitializeComponent();
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "csharp-Excel.xls");
string connStr = #"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(connStr);
string strCmd = "select * from [sheet1$A1:E7]";
SqlCommand cmd = new SqlCommand(strCmd, con);
try
{
con.Open();
ds.Clear();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
}
}
private void btnsend_Click(object sender, EventArgs e)
{
}
}
The error that I am getting is:
System.Data.SqlClient.SqlException: A network-related or instance-specified error occurred while establishing a connection to SQL Server
I think I got it working I made some changes in connection string :
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";
it is working on demo havent implement in actual project once I do will update.

Resources