Seeking help with code to move data from Excel file into a DataGrid and from DataGrid to SQL Server

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Sorry for all the posts everyone; I still haven’t gotten this working. Basically, I’m trying to update data in a SQL Server Table from a DataGrid.
<span style="font-family:Times New Roman,serif <br type="_moz

private void button4_Click(object sender, EventArgs e)<br/>
{<br/>
<br/>
DataTable dt = new DataTable("Import_List");<br/>
dataGridView1.DataSource = dt;<br/>
SqlConnection connection = new SqlConnection("Data Source=Excel-PC;Initial Catalog=Northwind.MDF;Trusted_Connection=True;");<br/>
SqlCommand cmd = new SqlCommand("Insert into Import_List (Fname, Lname, Age) Values (@Fname, @Lname, @Age)", connection);<br/>
cmd.Parameters.AddWithValue("@Fname", "");<br/>
cmd.Parameters.AddWithValue("@Lname", "");<br/>
cmd.Parameters.AddWithValue("@Age", "");<br/>
foreach (DataRow dataRow in dt.Rows)<br/>
{<br/>
using (connection)<br/>
{<br/>
connection.Open();<br/>
cmd.Parameters[0].Value = dataRow[1].ToString();<br/>
cmd.Parameters[1].Value = dataRow[2].ToString();<br/>
cmd.Parameters[2].Value = dataRow[3].ToString();<br/>
cmd.ExecuteNonQuery();<br/>
}<br/>
}<br/>
}
<span style="font-family:Times New Roman,serif
Also, I’m using this code to pull data from an Excel file into a DataGrid. Code is below:<span style="font-family:Times New Roman,serif <br type="_moz

DataTable table = new DataTable();<br/>
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text"",<br/>
"C:\Users\Excel\Desktop\Coding\DOT.NET\Samples C#\Export DataGridView to SQL Server Table\Import_List.xls");<br/>
using (OleDbConnection dbConnection = new OleDbConnection(strConn))<br/>
{<br/>
using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", dbConnection)) //rename sheet if required!<br/>
dbAdapter.Fill(table);<br/>
dataGridView1.DataSource = table;<br/>
int rows = table.Rows.Count;<br/>
}<br/>
<br/>
dataGridView1.AutoGenerateColumns = false;<br/>
dataGridView1.Columns["FName"].DataPropertyName = table.Columns["FName"].ColumnName;<br/>
dataGridView1.Columns["LName"].DataPropertyName = table.Columns["LName"].ColumnName;<br/>
dataGridView1.Columns["Age"].DataPropertyName = table.Columns["Age"].ColumnName;<br/>
dataGridView1.DataSource = table;<br/>
<br/>
When I step through the code nothing happens at all. Its like the DataTable is not recognized, or its not set, or some such thing. Can you help me get this straightened out??!!
<span style="font-family:Times New Roman,serif
<br/><hr class="sig Ryan Shuell

View the full article
 
Back
Top