How to QUICKLY Pass Data from a DataGrid to a SQL Server Table

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Ah, this still gets me. Im trying to invoke a Button_Click event and pass all data from a DataGrid to a SQL Server table. I found a code snippet posted by Mitja Bonca (below). Now, Im trying to fire the code by clicking a button.

private void button3_Click(object sender, EventArgs e)<br/>
{<br/>
<br/>
}<br/>
<br/>
class DAL //data access layer<br/>
{<br/>
<br/>
string connString = @"Server=excel-pc;Database=Northwind.MDF;Trusted_Connection=True;";<br/>
SqlDataAdapter da;<br/>
SqlCommandBuilder builder;<br/>
<br/>
public DataTable GetData()<br/>
{<br/>
DataTable table = new DataTable("dataGridView1");<br/>
SqlConnection conn = new SqlConnection(connString);<br/>
da = new SqlDataAdapter();<br/>
da.SelectCommand = new SqlCommand(@"SELECT * FROM Import_List", conn);<br/>
builder = new SqlCommandBuilder(da);<br/>
da.Fill(table);<br/>
return table;<br/>
}<br/>
<br/>
public void UpdateData(DataTable table)<br/>
{<br/>
if (da != null && builder != null)<br/>
{<br/>
builder.GetUpdateCommand();<br/>
da.Update(table);<br/>
}<br/>
}<br/>
}

The name of the DataGrid is dataGridView1 and the SQL ServerTable is named Import_List. Normally, you would enclose the operation inside the {} for the button. However, Im not sure hot to enclose a class!!

If I delete this line: class DAL //data access layer
As well as the associated {} marks, I get all kinds of errors.

Am I totally doing this wrong??? Is there a better way to do this??? <hr class="sig Ryan Shuell

View the full article
 
Back
Top