繁体   English   中英

如果自动生成主键,如何更新和删除数据库中的记录

[英]How to update and delete record in a database if primary key is auto generated

private void button2_Click(object sender, EventArgs e) 
{ 
    SqlConnection  con =  new  SqlConnection (strcon);

    string query = "update BrandSet set BrandName='" 
                   +  this.textBox1.Text  +  "', Ml = '" 
                   + this.textBox2.Text + "', Price='" 
                   +  this.textBox1.Text 
                   +  "' where Id = ";

    SqlCommand command = new SqlCommand(query, con);

    SqlDataReader adapt;

    try
    {
        con.Open();
        adapt = command.ExecuteReader();
        con.Close();

        MessageBox.Show("Brand Updated Successfully");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

我想知道如何分配Id以更新和删除记录。

我假设您正在单击一个按钮,并且它正在触发button2_Click 每个控件都有一个Tag属性,您可以在其中存储有关该控件的自定义数据。 您可以使用Tag存储正在加载的记录的id 我的意思是,在从db获取数据时,获取id并将其分配给控件的Tag然后单击控件时,从Tag获取其id。

// assigning Tag value
int id = // assign id
myControl.Tag = id;

更多细节在这里

您可以在按钮中使用CommandArgument。

<asp:Button ID="button2" runat="server" Text="Button2"  
     OnClick="button2_Click" CommandArgument="ID_Value"/>


private void button2_Click(object sender, EventArgs e) 
{ 
    if((String)e.CommandArgument != "")
    {
        id = (String)e.CommandArgument;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM