Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# windows窗体中显示空值的组合框的Textvalue_C#_Winforms - Fatal编程技术网

C# windows窗体中显示空值的组合框的Textvalue

C# windows窗体中显示空值的组合框的Textvalue,c#,winforms,C#,Winforms,我有一个windows窗体项目。我使用一个组合框来填充数据库中的一些数据。Combobox正确地显示了表中的数据,但问题是当我试图获取所选文本的文本值时,它显示空值。 这是密码 private void Form1_Load(object sender, EventArgs e) { loadCombobox("select designation, id from post order by id", txtDesignation, "designation",

我有一个windows窗体项目。我使用一个组合框来填充数据库中的一些数据。Combobox正确地显示了表中的数据,但问题是当我试图获取所选文本的文本值时,它显示空值。 这是密码

    private void Form1_Load(object sender, EventArgs e)
    {
        loadCombobox("select designation, id from post order by id", txtDesignation, "designation", "id");
    }

    private void loadCombobox(string query, ComboBox name, string itemField, string valueField)
    {
        using(SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=FIR_db; User Id = sa; Password = 9889922527"))
        {
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter(query, conn);
            conn.Open();
            DataSet ds = new DataSet();
            sda.Fill(ds, "post");
            name.DisplayMember = itemField;
            name.ValueMember = valueField;
            name.DataSource = ds.Tables["post"];
        }
        catch (SqlException exc)
        {
            DialogResult dr = MessageBox.Show("Error in server. Could not load Designation.", "Error in server", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        }
    }

    private void txtDesignation_SelectedIndexChanged(object sender, EventArgs e)
    {
       DialogResult dr = MessageBox.Show(txtDesignation.SelectedText.ToString(), "Error in server", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

此项目位于.net 4上,SelectedText只是控件中任何文本的突出显示部分


由于已设置ValueMember,请尝试改用SelectedValue属性。

您要访问的是
组合框。SelectedItem
属性

编辑:

从您的评论来看,您似乎正在用
DataRowView
对象填充
组合框。因此,您可能必须从行视图中获取感兴趣的值。试试这个:

dataRowView.Row["ColumnName"]

其中,
dataRowView
是您从组合框
中选择的项目。使用selectedItem.ToString时,您可能需要将其强制转换为
数据行视图

,它显示System.Data.DataRowViewyes我要获取所选文本/项,然后将其插入sql表,但插入后显示system.data.DataRowView,看起来您正在用
DataRowView
对象填充
ComboBox
。因此,您可能必须从行视图中获取感兴趣的值。尝试以下操作:
dataRowView.Row[“ColumnName”]
,其中dataRowView是您从组合框中选择的项目。您可能需要将其强制转换到
数据行视图
。我现在无法测试它,所以上面的所有内容只是一个一般性的建议。@VivekSingh,这很酷。自从这条评论成为解决你们问题的一部分,我就把它包括在主要答案中,为了子孙后代的利益。