简体   繁体   中英

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. It is designed for this purpose. You can assign the datasource to gridview and allow user to edit rows. 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? Anyway you need to investigate Bindings : BindingSource in WinForms or Binding class in WPF ( http://msdn.microsoft.com/en-us/library/ms750612.aspx ).

Look at DataTable events http://msdn.microsoft.com/en-us/library/system.data.datatable_events.aspx . There is RowChangedEvent. Call update sql command in its handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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