System.Data.DataRowView in DropDownList

天涯浪子 提交于 2019-11-30 18:11:21

问题


I am trying to populate a dropdown using values from a column. Now the problem is: I am not getting the actual values (the country codes like India(+61)) in the dropdown. Instead I am getting "System.Data.DataRowView" (multiple times) in the dropdown.

 public void bind()
 {
    DataSet ds1 = new DataSet();
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
    con.Open();
    string strQuery = "select CountryCode from AUser";
    SqlCommand cmd = new SqlCommand(strQuery, con);
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        da.Fill(ds1, "AUser");
    ddlMobile.DataSource = ds1.Tables["AUser"];
    ddlMobile.DataBind();
    con.Close();
}

I am calling the bind method on page_load. Data type for CountryCode is varchar(50) & values are like India(+91), Australia(+61) etc...


回答1:


You should set the DataValueField and DataTextField Properties of the drop down.

ddlMobile.DataSource = ds1.Tables["AUser"];
ddlMobile.DataValueField = "CountryCode";
ddlMobile.DataTextField = "CountryName";
ddlMobile.DataBind();

Here CountryCode and CountryName must be the column names corresponding to those values in your DataRow




回答2:


You are seeing what the default implementation of DataRowView.ToString() does. To pick specific fields from within the DataRow to display, do something like this.

ddlMobile.DataSource = ds1.Tables["AllUser"];
ddlMobile.DataTextField = "CountryCode"; // This is text displayed
ddlMobile.DataValueField = "CountryCode"; // This is the value returned
ddlMobile.DataBind();



回答3:


You haven't set the DataTextField in the DropDownList. It's recommended to set also the DataValueField In your aspx add the DataTextField property:

<asp:DropDownList ID="ddlMobile" runat="server" 
                  DataTextField="CountryCode"
                  DataValueField="CountryCode" />

You can also set it in the code behind, like the other answers show.

Otherwise the behaviour that you are seeing, is because the DataBound is calling the ToString() to display the info, as you don't provided wich data field look for.



来源:https://stackoverflow.com/questions/15522025/system-data-datarowview-in-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!