C# 将两列绑定到下拉列表中

C# 将两列绑定到下拉列表中,c#,asp.net,C#,Asp.net,我想将数据库中的两列绑定到dropdownlist中。这是我的密码: SqlConnection con=new SqlConnection(CommonRefference.Constr()); string query = "Select Id,Name+' ('+Distribution_name+') 'as Name1 from BR_supervisor "; SqlCommand cmd = new SqlCommand(query,con); con.Open(); Sql

我想将数据库中的两列绑定到dropdownlist中。这是我的密码:

SqlConnection con=new SqlConnection(CommonRefference.Constr());
string query = "Select Id,Name+' ('+Distribution_name+') 'as Name1 from BR_supervisor  ";

SqlCommand cmd = new SqlCommand(query,con);
con.Open();

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
        DropDownList3.DataSource = query;
        DropDownList3.DataTextField = "name1";
        DropDownList3.DataValueField = "Id";
        DropDownList3.DataBind();
}
con.Close();
但它给出了以下错误


数据绑定:“System.Char”不包含名为“name1”的属性

怎么做?任何帮助我的人都会受到高度赞赏

它的名字1而不是名字1

将此更改为

DropDownList3.DataTextField = "Name1";
编辑:

您正在将字符串(查询)绑定到此处的数据源

DropDownList3.DataSource = query;
字符串没有名为“name1”的属性,因此出现错误

解决方案:

请参阅此,我已根据您的要求更改了此内容

private void LoadDropDownList()
        {
            SqlConnection con=new SqlConnection(CommonRefference.Constr());
            string query = "Select Id,Name+' ('+Distribution_name+') 'as Name1 from BR_supervisor  ";

            SqlCommand cmd = new SqlCommand(query,con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            DropDownList3.DataSource = reader ;

            DropDownList3.DataValueField = "Id";
            DropDownList3.DataTextField = "Name1";

            DropDownList3.DataBind();

            DropDownList3.Items.Insert(0, new ListItem("Select One", "0")); // Adds items to the DDL
            DropDownList3.Items.Insert(1, new ListItem("All Categories", "-1"));

            con.Close();
        }
有关更多说明,请参阅此链接。问题在于:

DropDownList3.DataSource = query;
您将字符串值设置为源,因此它尝试将char值作为下拉列表的一项

所以,基本上您需要创建某种数据源(列表可能是一个好的数据源),然后通过您的阅读器填充它,然后您可以执行以下操作:

DropDownList3.DataSource = source;

数据绑定:“System.Char”不包含名为“Name1”的属性。请参考上面的解决方案,我已根据您的要求对此进行了更改。请您详细解释。我是asp.NET新手。您可能应该看看这两篇文章,它们将对您有所帮助。他们都有很好的例子