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);
Related
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());
}
}
}
}
I want update a SQL Server table from datagridview.
In my SQL Server table, I have columns no varchar(255) and golongan varchar(255)
And in the datagridview I have nip and gol
I want to update golongan with values gol from datagridview.
Here is example
1.Create a new Windows Forms application.
2.Create a database (named Sample). Add a table tbl_Record. The following is the table schema for creating tbl_Record.
3.Create a form (named frmMain) and drop a Label, TextBox, Button and DataGridView control from the ToolBox.
Now, go to the frmMain.cs code and add the System.Data and System.Data.SqlClient namespaces.
frmMain.cs Code
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
public frmMain()
{
InitializeComponent();
DisplayData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(#name,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Record",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Record set Name=#name,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Record where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}
In the preceding code, I created a dataGridView1_RowHeaderMouseClick Event for updating and deleting the selected record. When the user clicks on the Row Header of a row then the data present in the cell of the row is stored into the TextBoxes. The DisplayData() method fills in the data in the DataGridView.
The Clear() method clears the data present in the TextBox as well as in the ID(int) variable.
Final Preview
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);
I have two tables, one is dept and the other is emp with primary and foreign key relationship from emp.deptid which is a foreign key to dept.id. I have an aspx webpage and I have a dropdown list on it which I want to use to select dname form dropdown. But when I try to execute this code I get an error
Fill: SelectCommand.Connection property has not been initialized.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{ }
binddeptdropdown();
}
void binddeptdropdown()
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}
Your closing brace on your using function is in the wrong place, and your connection object needs to be passed to your function.
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
binddeptdropdown(con );
}
}
void binddeptdropdown(SQLConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}
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.