【问题标题】:In C#, How to use Selected Index with Combobox and Textbox在 C# 中,如何将选定索引与组合框和文本框一起使用
【发布时间】:2019-04-20 22:09:18
【问题描述】:

使用 selectedIndexChange for Combobox 填充 Access 数据库中的文本框。

我尝试过使用以下方法:

txtEventDate.Text = cboEventName.SelectedValue.ToString();

但它不会从选定的数据中填充。

// clear out listbox
cboEventName.Items.Clear();

// create instance of class
clsData myData = new clsData();

// send SQL statement to class
myData.SQL = "SELECT ID, EventName, EventDate FROM tblEvents ORDER BY EventName";

// loop through datatable to get values
for (int i = 0; i < myData.dt.Rows.Count; i++)
{
    // add customer to list box
    cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
    // add customer id to list
    string eventdate = ["EventDate"].ToString();
    txtEventDate.Text = cboEventName.SelectedValue.ToString();
    // txtEventDate trying to fill from combobox entry and it isn't showing the date from the access.
    intEventID.Add(int.Parse(myData.dt.Rows[i]["ID"].ToString()));
}

【问题讨论】:

  • 如果您的“EventDate”来自 mydate。然后设置你的 myData.dt.Rows[i]["EventDate"].ToString()
  • 请添加断点并检查每一行。并且看到 mydata 有一些数据列表并且 cboEventName 正在填充。然后在设置 txtEventDate 之前检查 eventDate 你得到的值
  • 我可以让组合框填充,但日期不会填充文本字段。
  • 我尝试了您的建议,但组合框没有填写,但事件日期使用一个固定日期而不是基于组合框的选择
  • 在您的 foreach 条件中再添加一个 if 条件以匹配您为组合框选择的索引,然后设置您的 eventdate(string) 字段。现在它正在为 Mydata 列表中的每个数据进行设置。

标签: c# sql database combobox textbox


【解决方案1】:

尝试像这样为选定索引值设置 EventDate。如果 SelectedValue 与 MyData 行索引匹配,则设置事件日期。

for (int i = 0; i < myData.dt.Rows.Count; i++)
            {
                // add customer to list box
                cboEventName.Items.Add(myData.dt.Rows[i]["EventName"].ToString());
                // add customer id to list
                if(cboEventName.SelectedValue.ToString() ==myData.dt.Rows[i]["EventName"].ToString())
                    string eventdate = ["EventDate"].ToString();
                txtEventDate.Text = cboEventName.SelectedValue.ToString();
            }

【讨论】:

  • hmmm 好的,但是我在字符串 eventdate = [] 处遇到错误。它说'['无效的表达。我是否在此声明中遗漏了一些额外内容?
  • 像这样修改你的 eventdate 代码。字符串事件日期 =myData.dt.Rows[i] ["EventDate"].ToString();
  • 我会使用字符串并让它指向 txtEventDate.Text 吗? txtEventDate.Text = eventdate 之类的东西?然后它应该可以工作
  • 它现在在 if (cboEventName...) 状态下出错 对象引用未设置为对象的实例。
  • 代码中哪一行抛出错误。做断点并首先检查。还要检查你是否获得了 cboEventName.SelectedValue.ToString() 的价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多