C# - 在Windows Forms应用程序中获取SelectedItem的值

3

我有一个简单的 Windows Forms 应用程序(带有 Access 数据库),其中有一个组合框(cmbStores),它以最简单的方式填充。

问题:我无法获取所选项目的值。

以下是我如何填充这个组合框:

// Variable declaration
        string strQueryStores = "SELECT StoreNumber FROM tblStoresAndRegion ORDER BY StoreNumber";
        string strConnectionString = UtilityClass.GetConnectionString();
        OleDbConnection connStores;
        OleDbDataReader readerStores = null;

        connStores = new OleDbConnection(strConnectionString);

        try
        {
            connStores.Open();
            OleDbCommand sqlGetStores = new OleDbCommand(strQueryStores, connStores);

            cmbStore.Items.Clear();
            cmbStore.Items.Add("All");
            if (connStores != null)
            {
                readerStores = sqlGetStores.ExecuteReader();

                if (readerStores.HasRows)
                {
                    while (readerStores.Read())
                    {
                        cmbStore.Items.Add (Convert.ToInt32(readerStores["StoreNumber"]));
                    }
                }
            }
            cmbStore.SelectedIndex = 0;

        }

        catch (OleDbException oledblEX)
        {
            MessageBox.Show(oledblEX.Message);
        }

        finally
        {
            if (readerStores != null)
                readerStores.Close();
            if (connStores != null)
                connStores.Close();
        }

这是我尝试获取所选项值的方式。

int nStoreNumber = Convert.ToInt32(cmbABSM.SelectedItem);

你所使用的获取选定项的代码在哪里?你是否遇到异常?值不正确吗?当您尝试获取选定项时发生了什么? - Khan
1
你的代码存在一些不一致。你填充了_cmdStore_框,然后尝试读取_cmbABSM_框。这是真的吗,还是你打错了? - Matzi
@Matzi...我打错了。代码应该是int nStoreNumber = Convert.ToInt32(cmbStore.SelectedItem); - KalC
已解决(但仍感困惑)... 当我使用以下代码 int nStoreNumber = Convert.ToInt32(cmbStore.Text); 时,它可以正常运行。 - KalC
4个回答

4

如果为组合框设置了ValueMember,请尝试使用SelectedValue,否则默认使用Text属性:

//If ValueMember is set
int nStoreNumber = Convert.ToInt32(cmbABSM.SelectedValue);

//Otherwise
int nStoreNumber = Convert.ToInt32(cmbABSM.Text);

无论哪种方式,我建议您确保所选的值是有效的int
int nStoreNumber;

if (!int.TryParse(cmbABSM.SelectedValue, out nStoreNumber))
{
    //This is not a valid number.  Notify the user.
}

4

我知道我有点晚了,但这个方法很有效:

int? nStoreNumber = cmbABSM.SelectedValue as int?;
if (nStoreNumber==null)
    return;

2

does

Int32.Parse(box.SelectedItem.ToString());

你需要我为你工作吗?


2
你应该真正使用项目上的“Value”或“Text”属性。读者不清楚“ToString”返回哪个属性。 - Servy

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接