简体   繁体   English

使用C#编辑由SQL查询数据源填充的列表框的内容

[英]Editing contents of a listbox that is populated by a sql query datasource using c#

I have a list box that is populated by a query result set, i would to give the user the ability to edit the contents of the list box, and update the database back end, how can i achieve this? 我有一个由查询结果集填充的列表框,我希望使用户能够编辑列表框的内容并更新数据库后端,我该如何实现呢?

public Brand_Manager(Main parent)
{
SqlConnection conn = new     SqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString.ToString());
        SqlCommand cmd = new SqlCommand("select Brand_ID, Brand_Name from Brand where status=1", conn);
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable t = new DataTable();
        da.Fill(t);
        listBox1.DisplayMember = "Brand_Name";
        listBox1.DataSource = t;
        listBox1.ValueMember = "Brand_ID";

        conn.Close();
}
 private void Edit_Button_Click(object sender, EventArgs e)
    {
        this.Edit_Button.Enabled = false;
        object item = listBox1.SelectedItem;
         Edit_Brand frm = new Edit_Brand();
        this.AddOwnedForm(frm);
        frm.ShowDialog();

    }

You need to use datagridview for this purpose. 为此,您需要使用datagridview。 It is designed for this purpose. 为此目的而设计。 You can assign the datasource to gridview and allow user to edit rows. 您可以将数据源分配给gridview并允许用户编辑行。 Then by handling row edited event or by giving the button you can update the database. 然后,通过处理行编辑事件或通过提供按钮,可以更新数据库。 See an example here 在这里查看示例

Do you use WPF or WinForms? 您使用WPF还是WinForms? Anyway you need to investigate Bindings : BindingSource in WinForms or Binding class in WPF ( http://msdn.microsoft.com/en-us/library/ms750612.aspx ). 无论如何,您都需要研究WinForms中的BindingsBindingSource或WPF中的Binding类( http://msdn.microsoft.com/zh-cn/library/ms750612.aspx )。

Look at DataTable events http://msdn.microsoft.com/en-us/library/system.data.datatable_events.aspx . 查看DataTable事件http://msdn.microsoft.com/zh-cn/library/system.data.datatable_events.aspx There is RowChangedEvent. 有RowChangedEvent。 Call update sql command in its handler. 在其处理程序中调用update sql命令。

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

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