|
请问各位大虾,如何在DATAGRID中实现编辑功能,我用的是C#,找了一些资料,但是功能还是未能实现,下面是我的代码,请问各为我到底应该如何修改,非常谢谢。
public void DataGrid1_EditCommand(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = (int)E.Item.ItemIndex;
LoadDatebase();//打开数据库
string MyComStr="select pclass_id,pclass_name from pclass";
sqlCommand1=new SqlCommand(MyComStr,this.myConnect);
sqlDataAdapter1=new SqlDataAdapter();
sqlDataAdapter1.SelectCommand=sqlCommand1;
sqlDataAdapter1.Fill(ClassDaSet,"p_signup");
DataGrid1.DataSource=ClassDaSet.Tables["p_signup"].DefaultView;
DataGrid1.DataBind();
}
public void DataGrid1_CancelCommand(Object sender, DataGridCommandEventArgs E)
{
DataGrid1.EditItemIndex = -1;
LoadDatebase();//打开数据库
string MyComStr="select pclass_id,pclass_name from pclass";
sqlCommand1=new SqlCommand(MyComStr,this.myConnect);
sqlDataAdapter1=new SqlDataAdapter();
sqlDataAdapter1.SelectCommand=sqlCommand1;
sqlDataAdapter1.Fill(ClassDaSet,"p_signup");
DataGrid1.DataSource=ClassDaSet.Tables["p_signup"].DefaultView;
DataGrid1.DataBind();
}
public void DataGrid1_UpdateCommand(Object sender, DataGridCommandEventArgs E)
{
//string MyComStr="select pclass_id,pclass_name from pclass";
String updateCmd = "UPDATE pclass SET pclass_id = @Id, pclass_name = @Name";
SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);
myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NChar, 1));
myCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 50));
;
myCommand.Parameters["@Id"].Value = DataGrid1.DataKeys[(int)E.Item.ItemIndex];
String[] cols = {"@Id","@Name"};
int numCols = E.Item.Cells.Count;
for (int i=1; i<numCols-1; i++) //跳过第一、第二和最后一列
{
String colvalue =((TextBox)E.Item.Cells[i].Controls[0]).Text;
// 检查在所需字段中是否有空值
if (colvalue == "")
{
Message.InnerHtml = "错误:“类别名称”不允许使用空值";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
//追加最后一行,将 true/false 值转换为 0/1
if (String.Compare(((TextBox)E.Item.Cells[numCols-1].Controls[0]).Text, "True", true)==0)
myCommand.Parameters["@Contract"].Value = "1";
else
myCommand.Parameters["@Contract"].Value = "0";
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>已更新记录</b><br>" + updateCmd;
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录";
else
Message.InnerHtml = "错误:未能更新记录,请确保正确填写了字段";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
LoadDatebase();//打开数据库
string MyComStr="select pclass_id,pclass_name from pclass";
sqlCommand1=new SqlCommand(MyComStr,this.myConnect);
sqlDataAdapter1=new SqlDataAdapter();
sqlDataAdapter1.SelectCommand=sqlCommand1;
sqlDataAdapter1.Fill(ClassDaSet,"p_signup");
DataGrid1.DataSource=ClassDaSet.Tables["p_signup"].DefaultView;
DataGrid1.DataBind();
}
老提示“MESSAGE”有问题,请问我应该如何定义MESSAGE,还有各位麻烦帮看一下,到底这个代码问题出在那里,不能修改,也不能更新,晕啊,初来乍到,有点不好意思,问题很幼稚,能解决很感激。 |
|