|
Subject:
|
Inserting data into DataGrid
|
|
Posted By:
|
edurazee
|
Post Date:
|
7/25/2008 6:16:18 AM
|
Can anyone show me how to insert new row data into DataGrid cells and persist the changes in the DB?
The condition is, the total code must be coded by hand.
The reason is, I have written a DB manipulation class. And, the DataGrid data insertion code must work with that.
I have found a similar project on codeproject.comUsing the DataGrid Control
By Huseyin Altindag but the author used Visual Studio drag-drop feature to add a DataSet control. So the code came with different functionality.
|
|
Reply By:
|
DZukiewicz
|
Reply Date:
|
7/28/2008 5:51:13 PM
|
Well, DataGrids are fairly flexible, so do what you need to with DataTables and then use that to insert into a database. I'll do a small demo from the .cs perspective, not the in-line ASPX code:
DataTable dt = new DataTable("MyTable");
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("Name",typeof(string));
dt.Rows.Add( new object[] { 1,"Joe" } );
dt.Rows.Add( new object[] { 2,"Bob" } );
dt.Rows.Add( new object[] { 3,"Jim" } );
dt.Rows.Add( new object[] { 4,"Mick" } );
dt.Rows.Add( new object[] { 5,"Dave" } );
ViewState["DataTable"] = dt;
DataGrid dg = new DataGrid();
dg.AutoGenerateColumns = true;
dg.DataSource = dt;
dg.DataBind();
Binding to a database could be similar to...
DataTable dt = ViewState["DataTable"] as DataTable;
SqlConnection sqlConn = new SqlConnection("Data Source=localhost;Initial Catalog=mydb;Integrated Security=SSPI");
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandText = "INSERT INTO MyTable (Id,Name) VALUES @Id, @Name";
sqlComm.CommandType = System.Data.Common.CommandType.Text;
sqlCommn.Parameters.Add("@Id", SqlDbType.Int, 4, "Id");
sqlCommn.Parameters.Add("@Name", SqlDbType.VarChar, 10, "Name");
using(SqlDataAdapter da = new SqlDataAdapter(sqlComm))
{
da.Fill(dt);
}
Does that help at all?
Dominic
|