日期:2014-05-20  浏览次数:20822 次

c#中数据库更新问题,急!在线等
请问,我现在已经在datagridview中显示了相关表的内容,并通过datagridview中的datagridview.Rows[e.RowIndex].Cells[i].Value.ToString()给下面的textBox赋值,现在我想通过对textBox的修改来更新数据库,怎么办?

------解决方案--------------------
听过gridview不编码就能完成察看 增 删 改 的操作,不过没实现过,哪位高人知道的话指点下迷津

下面是我的笨方法--编码实现的update操作:
//conn是连接字符串
SqlDataAdapter da = new SqlDataAdapter( "select * from res where id= " + id,conn);
da.MissingSchemaAction = System.Data.MissingSchemaAction.AddWithKey;
SqlCommandBuilder scb = new SqlCommandBuilder(da);
da.Fill(dt);
System.Data.DataRow row = dt.Rows[0];
row[ "name "] = TextBox1.Text;
da.Update(dt);
------解决方案--------------------
sql = "update Role set Rolename=@Rolename,ModifyDate=@ModifyDate,Modifier=@Modifier,Description=@Description where sId=@sId ";
cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add( "@Rolename ", SqlDbType.NChar, 40, "Rolename ");
cmd.Parameters.Add( "@ModifyDate ", SqlDbType.DateTime,12, "ModifyDate ");
cmd.Parameters.Add( "@Modifier ", SqlDbType.NChar, 40, "Modifier ");
cmd.Parameters.Add( "@Description ", SqlDbType.NChar, 40, "Description ");
cmd.Parameters.Add( "@sId ", SqlDbType.NChar, 40, "sId ");

cmd.Parameters[ "@sId "].Value = sId;
cmd.Parameters[ "@Rolename "].Value = Rolename;
cmd.Parameters[ "@ModifyDate "].Value = ModifyDate;
cmd.Parameters[ "@Modifier "].Value = modifier;
cmd.Parameters[ "@Description "].Value = Description;


cmd.ExecuteNonQuery();

ManageConn.freeConnection(conn);
------解决方案--------------------
我给一个比较笨的方法,我在做的时候是采用这个方法的,大家不要笑啊.
定义一个变量;public static int num; 在DATAGRIDE的EDIT_COMMAND 事件中用num记录下当前的行数语句;num=(int)e.Item .ItemIndex ;,然后在更新按钮中加入更新代码即可.更新代码如下:(其中LoadDataBase是自定义的函数,用来打开数据库,声明了public SqlCommandBuilder objcmdBuilder;用来更新库,更新库后重新进行了绑定,以实现在DATAGRIDE中显示更新后的信息)
string MyComStr;

LoadDatebase();//打开数据库
MyComStr= "select login_id,password,admin_right,last_time from p_admin ";
sqlCommand1=new SqlCommand(MyComStr,this.myConnect);
sqlDataAdapter1=new SqlDataAdapter();
sqlDataAdapter1.SelectCommand=sqlCommand1;
sqlDataAdapter1.Fill(ClassDaSet, "p_signup ");
if (Text_2.Text .Trim ()== " "||Text_21.Text .Trim ()== " "||Text_2.Text .Trim ()!=Text_21.Text .Trim ())
{
System.Web.HttpContext.Current.Response.Write( " <script language=javascript> window.alert( '密码不能为空或者两次密码输入不一致! ') </script> ");
System.Web.HttpContext.Current.Response.End();
}
string code = Text_2.Text .Trim ();
string code1 = Text_3.Text .Trim ();;

//将得到的数据赋予数据集ClassDaSet相应的字段中,以备下面的更新语句写入数据库
ClassDaSet.Tables[ "p_signup "].Rows[yhgl_currentnum][1]=code;
ClassDaSet.Tables[ "p_signup "].Rows[yhgl_currentnum ][2]=code1;

//----------------------

objcmdBuilder = new SqlCommandBuilder(sqlDataAdapter1);
sqlDataAdapter1.UpdateCommand = objcmdBuilder.GetUpdateCommand();