【问题标题】:How to get first item from comboxbox in c#?如何从 C# 中的组合框中获取第一项?
【发布时间】:2021-01-05 03:06:06
【问题描述】:

我用这个代码用数据库中的两列填充一个组合框:

            foreach (DataRow dr2 in dt2.Rows)
            {
                comboBox1.Items.Add(dr2["Station"].ToString() + " - " + dr2["Ime"].ToString());
            }
            dbconn.Close();

组合框看起来像这样:

现在我只想从这个组合框中取出第一项(数字)并放入我的查询中以获取数据库中的数据。

我希望变量 Stations 与组合框中的第一个项目一起使用。

我尝试从组合框中获取第一个索引,但是当我调试时,我看到变量的值每次都是 -1..

代码:

        var Stations = comboBox1.SelectedIndex = -1;

        MySqlCommand cmd = new MySqlCommand("CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('"+ dtnow +"', " + Stations + ", 5)", dbconn);
        MySqlDataAdapter da = new MySqlDataAdapter();
        dbconn.Open();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        da.Fill(ds);
        dt = ds.Tables[0];

        foreach (DataRow dr in dt.Rows)
        {
            dataGridView1.DataSource = dt;
        }
        dbconn.Close();

我从调试模式上传一张图片:

【问题讨论】:

  • 这能回答你的问题吗? How to take only first index from combobox c#
  • 我不明白,你不是已经得到答案了吗?但如果是另一个问题,您应该更改标题并表明它是另一个主题,与上一个问题相关,以及更改此处相同的文本开头。否则,它就像同一个问题,有更多细节和一些变化。
  • 编写var Stations = comboBox1.SelectedIndex = -1; 将Stations 设置为-1,并将comboBox1.SelectedIndex 设置为-1,因此您确实每次都有-1。
  • comboBox1.SelectedIndex = -1; 基本上删除了选择。这是故意的吗?
  • @Mong Zhu 确实如此。我不认为这是这里的目标,而是问题的根源。

标签: c# .net winforms combobox


【解决方案1】:

我希望变量 Stations 与组合框中的第一项一起出现

代替

var stations = comboBox1.SelectedIndex = -1;

使用

comboBox1.SelectedIndex = -1;
var stations = comboBox1.SelectedText; // or Text

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多