我有一个包含4列的数据网格视图:UserID, FirstName, LastName, Email
当我双击一行时,另一个表单会弹出4个文本框,其中包含行的值,每个文本框都带有单元格值
当我点击提交按钮时,该行会使用文本框值进行更新。
我与....where UserID = @UserID
合作的内容。但如果是一个列单元格
我改变了IS UserId
,错误的行或没有行,会被修改。
问题
如何为任何列值编辑行,并且在没有增量列的情况下更改右行?
代码
public partial class EditUser : Form
{
public DataGridViewRow dgvRow;
public EditUser()
{
InitializeComponent();
}
private void EditUser_Load(object sender, EventArgs e)
{
lbl5.Text = dgvRow.Cells[0].Value.ToString();
txtUserID.Text = dgvRow.Cells[0].Value.ToString();
txtFName.Text = dgvRow.Cells[1].Value.ToString();
txtLName.Text = dgvRow.Cells[2].Value.ToString();
txtEmail.Text = dgvRow.Cells[3].Value.ToString();
label1.Visible = false;
txtUserID.Visible = false;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("");
sc.Open();
com.Connection = sc;
com.CommandText = ("update JoshUserTable SET UserID = @UserID, FirstName=@FirstName,LastName=@LastName,Email=@Email where UserID = @UserID");
com.Parameters.AddWithValue("@UserID", txtUserID.Text);
com.Parameters.AddWithValue("@FirstName", txtFName.Text);
com.Parameters.AddWithValue("@LastName", txtLName.Text);
com.Parameters.AddWithValue("@Email", txtEmail.Text);
com.ExecuteNonQuery();
sc.Close();
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
label1.Visible = true;
txtUserID.Visible = true;
SqlConnection sc = new SqlConnection();
SqlCommand con = new SqlCommand();
sc.ConnectionString = ("");
sc.Open();
con.Connection = sc;
con.CommandText = ("update JoshUserTable SET UserID = @UserID, FirstName=@FirstName,LastName=@LastName,Email=@Email where FirstName = @FirstName");
con.Parameters.AddWithValue("@UserID", txtUserID.Text);
con.Parameters.AddWithValue("@FirstName", txtFName.Text);
con.Parameters.AddWithValue("@LastName", txtLName.Text);
con.Parameters.AddWithValue("@Email", txtEmail.Text);
con.ExecuteNonQuery();
sc.Close();
}
}
答案 0 :(得分:0)
我认为你正在遇到一个更大的问题。如果另一个用户同时更改记录该怎么办?您将运行并发问题。这就是自动生成的CommandBuilder代码始终检查旧值的原因。
对于您当前的代码,我添加了对原始用户ID 的检查。
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("My Connection String");
sc.Open();
com.Connection = sc;
/// check for original value in whereClause
com.CommandText = ("update JoshUserTable SET UserID = @NEW_UserID,
FirstName=@FirstName,LastName=@LastName,Email=@Email
where UserID = @ORIGINAL_UserID");
com.Parameters.AddWithValue("@NEW_UserID", txtUserID.Text);
com.Parameters.AddWithValue("@ORIGINAL_UserID", INSERT_ORIGINAL_USERID);
com.Parameters.AddWithValue("@FirstName", txtFName.Text);
com.Parameters.AddWithValue("@LastName", txtLName.Text);
com.Parameters.AddWithValue("@Email", txtEmail.Text);
com.ExecuteNonQuery();
sc.Close();
}
并发问题仍未得到解决....