日期:2014-05-19  浏览次数:20801 次

重新发贴DataGrid的问题。
如何在点击编辑按钮时把想要的行的值保存到一个变量里?

就是在UpdateCommand   事件   去更新数据到数据库   要提交一条SQL语句


string   updatestr= " ";
updatestr+= "pettype= ' "+((TextBox)e.Item.Cells[2].Controls[0]).Text+ " ' ";
updatestr+= ",petname= ' "+((TextBox)e.Item.Cells[3].Controls[0]).Text+ " ' ";
updatestr+= ",petage= ' "+((TextBox)e.Item.Cells[4].Controls[0]).Text+ " ' ";


提交一个SQL语句
update   petinformation   set   "+updatestr+ "where   petname= ' "+tempetname+ " '   and   petage= ' "+tempetage+ " ' ";

其中   tempetname   和tempetage   要要回原来的值才可以在数据库中查询到那条记录啊。
((TextBox)e.Item.Cells[2].Controls[0]).Text     这个已经是在   DataGrid1   控件上的新值了。所以不可能
update   petinformation   set   "+updatestr+ "where   petname= ' "+((TextBox)e.Item.Cells[2].Controls[0]).Text     + " ' "……那样去找啊


=============如何在点击编辑按钮时把想要的行的值保存到一个变量里?

private   void   DataGrid1_EditCommand(object   source,   System.Web.UI.WebControls.DataGridCommandEventArgs   e)
{

DataGrid1.EditItemIndex=e.Item.ItemIndex;


tempetname=((TextBox)e.Item.Cells[2].Controls[0]).Text;

}

为什么说
指定的参数超出范围呢?
参数名:index


------解决方案--------------------
你去更新的条件不对,应该是根据主键更新

正规做法是在绑定DataGrid的时候设置DataKeyField属性为你的表的主键

然后更新的时候通过DataGrid1.DataKeys[e.Item.ItemIndex].ToString()得到你的主键值

给段参考代码

private void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
SqlConnection cn = new SqlConnection( connectionString);
string strUpdate = "update aa set bb=1 set id=@id ";
SqlCommand cmd = new SqlCommand(strUpdate, cn );
//记得在前台设置DataGrid的DataKeyField为aa表的主键字段
cmd.Parameters.Add( "@id ", SqlDbType.VarChar).Value = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
DataGrid1.EditItemIndex = -1;
BindDataGrid(); //这个是重新邦定DataGrid的方法

}