提问人:Salem Gogah 提问时间:11/17/2023 更新时间:11/18/2023 访问量:68
允许通过组合框下拉列表添加新记录
Allow add new record through combobox dropdown list
问:
我有 Combobox,这是来自客户表的数据源
combo_customers.DataSource = AddingDebit_con.Get_All_Customers();
combo_customers.DisplayMember = "customer_fullname";
combo_customers.ValueMember = "customer_id";
AddingDebit_con
是 .cs 文件包含以下代码
public DataTable Get_All_Customers()
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
DataTable dt = new DataTable();
dt = DAL.SelectData("All_customers", null);
return dt;
}
DAL
是包含 sql-connection 的文件夹DataAccessLayer.cs
All_customers
是一个 SQL 服务器过程,如下所示
ALTER proc [dbo].[All_customers] AS select customer_fullname,customer_id from Customers
上面的一切都按照我的意愿工作,但客户问我是否可以直接从组合框添加新客户,以防客户未在表源中列出(组合框下拉列表)
Combobox 显示成员 (Customer_name) 但插入值 (customer_id) 的问题!
答:
0赞
mhmtensyldrm
11/17/2023
#1
如果组合框的 DropDownStyle 设置为“DropDownList”,则只能选择该组合框中的现有记录。
首先,您应该将该组合框的 DropDownStyle 更改为“DropDown”。在此之后,组合框的文本是可编辑的,您可以插入新记录。
为插入创建一个新的存储过程,并将该组合框文本作为客户名称参数发送。如果 ID 列没有自动增加,您可以创建 SQL FUNCTION 来获取表的最后一个 ID,并在客户端增加该 ID,并将其作为客户 ID 参数发送。
但我不建议这样做。应为 CreateCustomer 操作创建一个新窗体,并且可以在该窗体中使用文本框。
0赞
Salem Gogah
11/18/2023
#2
我找到了答案。我在重新加载表单中使用了 if 条件:
if (combo_customers.SelectedValue == null )
{
// first get the value of new customer's ID which = last ID+1
int amount = Convert.ToInt32(CustomersMangment.dgv_search.Rows[CustomersMangment.dgv_search.Rows.Count - 2].Cells[0].Value);
int total = amount + 1;
addingCustomers.tb_phone.Text = "";
addingCustomers.comb_addess.Text = "text";
addingCustomers.tb_CustomerName.Text = combo_customers.Text;
addingCustomers.dtp_addingDate.Value = DateTime.Now;
AddingDebit_con.InsertCustomer(addingCustomers.tb_CustomerName.Text, addingCustomers.tb_phone.Text, addingCustomers.comb_addess.Text, addingCustomers.dtp_addingDate.Value);
//2nd reload the form to reload combobox items
AddinDebits_Load(null, EventArgs.Empty);
combo_customers.SelectedValue = total;
// Adding cmd
AddingDebit_con.AddingNewDebit(int.Parse(combo_customers.SelectedValue.ToString()), dtp_addingDebit.Value, Convert.ToInt32(tb_amount.Text));
MessageBox.Show("done");
tb_amount.Text = "";
tb_date.Text = "";
dtp_addingDebit.Value = DateTime.Now;
//Refresh
this.dgv_withdraw.DataSource = AddingDebit_con.DataGrid_Withdraw();
lbl_total.Text = combo_withdrawTotal.Text;
}
else {
AddingDebit_con.AddingNewDebit(int.Parse(combo_customers.SelectedValue.ToString()), dtp_addingDebit.Value, Convert.ToInt32(tb_amount.Text));
MessageBox.Show("done");
tb_amount.Text = "";
tb_date.Text = "";
dtp_addingDebit.Value = DateTime.Now;
//Refresh
this.dgv_withdraw.DataSource = AddingDebit_con.DataGrid_Withdraw();
lbl_total.Text = combo_withdrawTotal.Text;
}
评论
0赞
Jeremy Caney
11/18/2023
感谢您对 Stack Overflow 社区的贡献。这可能是一个正确的答案,但提供代码的额外解释,以便开发人员能够理解你的推理,这将是非常有用的。这对于不熟悉语法或难以理解概念的新开发人员特别有用。为了社区的利益,您能否编辑您的答案以包含其他详细信息?
评论
DataSource
DisplayMember
ValueMember