Reputation: 31
Here is my exceedingly simple test dropdown list:
<asp:DropDownList runat="server" ID="Test" />
Here is my code behind:
protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Value", typeof(Int32))); dt.Columns.Add(new DataColumn("Text", typeof(String))); DataRow dr = dt.NewRow(); dr[0] = 1; dr[1] = "Test of text"; dt.Rows.Add(dr); Test.DataSource = "dt"; Test.DataValueField = "Value"; Test.DataTextField = "Text"; Test.DataBind(); }
When I try to load the page I get the following error:
Server Error in '/' Application.
DataBinding: 'System.Char' does not contain a property with the name 'Text'.
Does anyone have any ideas as to what is going on here?
Upvotes: 0
Views: 166
Reputation: 10295
Dt
is Not a String it is Variable
and Check For AutoPostBack
So that DropDownList
will Bind Only Once.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Value", typeof(Int32)));
dt.Columns.Add(new DataColumn("Text", typeof(String)));
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "Test of text";
dt.Rows.Add(dr);
Test.DataSource = dt;
Test.DataValueField = "Value";
Test.DataTextField = "Text";
Test.DataBind();
}
}
Upvotes: 1
Reputation: 318
You should reference DataSource this way:
Test.DataSource = dt;
to refer to DataTable object, not "dt" string.
Upvotes: 1