给你点代码吧,我自己参考着书写的,你好好研究研究,有什么不懂了,随时找我吧..首先你必须确定当前行是可以编辑的,以下代码是选择当前行是可编辑的:protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex=e.Item.ItemIndex;
bindData();
}
然后你就可以更新了,updatestr为要更新的变量
protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
string connStr = "server=localhost;uid=sa;pwd=sa;database=myWebDB";
SqlConnection myconnection = new SqlConnection(connStr);
string updatestr = "";
updatestr+="bookid='"+((TextBox)e.Item.Cells[2].Controls[0]).Text+"'";//其中((TextBox)e.Item.Cells[2].Controls[0])为取得当前行的第3个单元格也就是文本框了。把它的内容赋给字段
updatestr += ",bookname='" + ((TextBox)e.Item.Cells[3].Controls[0]).Text + "'";
updatestr += ",author='" + ((TextBox)e.Item.Cells[4].Controls[0]).Text + "'";
updatestr += ",publisher='" + ((TextBox)e.Item.Cells[5].Controls[0]).Text + "'";
updatestr += ",price='" + ((TextBox)e.Item.Cells[6].Controls[0]).Text + "'";
string updatecomm = "update book_inf set " + updatestr + "where bookid='" + DataGrid1.DataKeys[e.Item.ItemIndex] + "'";
SqlCommand myupdate = new SqlCommand(updatecomm, myconnection);
try
{
myconnection.Open();
myupdate.ExecuteNonQuery();
Response.Write("");
}
catch
{
Response.Write("");
}
finally
{
myconnection.Close();
}
bindData();
更新的原理就是通过创建sqlcommand对象,然后利用更新的语句,更新数据库。删除的原理也是这。
private void bindData()
{
string connStr = "server=localhost;uid=sa;pwd=sa;database=myWebDB";
SqlConnection myconnection = new SqlConnection(connStr);
//myconnection.Open();
string queryStr = "select * from book_inf";
SqlDataAdapter myDataAdapter = new SqlDataAdapter(queryStr, myconnection);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "books");
if (myDataSet.Tables["books"].Rows.Count > 0)
{
Label1.Text = "所有图书登记";
DataGrid1.DataSource = myDataSet.Tables["books"].DefaultView;
DataGrid1.DataBind();
}
else
{
Label1.Text = "没有图书登记";
DataGrid1.Visible = false;
}
gridview里面什么都有,不用另写代码,只要绑定了sqldatasource,并在gridview中开启各操作直接使就行,
绑定sqldatasource,对sqldatasource配置数据源时有一个高级按钮,在那里打开对数据源的各项操作,并在gridview的属性中设置自动添加增删查改按钮
修改datagridview后触发事件 保存dataGridView中信息
轮询绑定在datagridview中的表:
DataTable dt = (DataTable)dataGridView1.DataSource;
foreach (DataRow dr in dt.Rows)
{
//根据行的状态决定对数据库接行什么操作
switch (dr.RowState)
{
case DataRowState.Added:
//把这一行添加回数据库
bllRebateType.InsertData();
break;
case DataRowState.Deleted:
//把数据库里的这一行删除
bllRebateType.DeleteDate(dr["ID", DataRowVersion.Original].ToString());
break;
case DataRowState.Modified:
//更新数据库里的该条记录
bllRebateType.UpdateData();
break;
}
}