Reputation: 41
I have 7 dropdown lists for the the hours of the day for each each day.
Instead of typing datasource
, textfield
, and valuefield
for each drop down, I decided to create a small code that will iterate through an enum and append at the end the day of the week.
However I get an error : Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.DropDownList'.
The line ((DropDownList)strTimeFrom).DataSource = TimesAvailable();
Doesn't show any error at run time.
enum Days
{
Sunday = 1,
Monday = 2,
Tuesday = 3,
Wednesday = 4,
Thursday = 5,
Friday = 6
}
protected void Page_Load(object sender, EventArgs e)
{
foreach (Days day in Enum.GetValues(typeof(Days)))
{
object strTimeFrom = "ddlTimeFrom" + day;
object strTimeTo = "ddlTimeTo" + day;
((DropDownList)strTimeFrom).DataSource = TimesAvailable();
((DropDownList)strTimeFrom).DataTextField = "Value";
((DropDownList)strTimeFrom).DataValueField = "Key";
((DropDownList)strTimeFrom).DataBind();
}
}
protected List<KeyValuePair<int, string>> TimesAvailable()
{
List<KeyValuePair<int, string>> lstTime = new List<KeyValuePair<int, string>>();
lstTime.Add(new KeyValuePair<int, string>(-1, "--Select Time---"));
for (int intCnt = 1; intCnt <= 12; intCnt++)
{
lstTime.Add(new KeyValuePair<int, string>(intCnt, intCnt.ToString()));
}
return lstTime;
}
Upvotes: 2
Views: 1632
Reputation: 1884
You're getting that at runtime because you're trying to cast a string to a DropDownList. You might think that declaring strTimeFrom
as object, and appending the day name to get your actual DropDownList, is going to work - but it won't. At the end of the day, strTimeFrom/To
are strings and you cannot cast those as DropDownList.
In your case, you should declare these variables as string, and try
var list = Page.FindControl(strTimeFrom) as DropDownList;
list.DataSource = TimesAvailable();
list.DataTextField = "Value";
list.DataValueField = "Key";
list.DataBind();
As a rule you should not declare variables as object, particularly if you really want intrinsic types due to the boxing overhead. C# is a strongly-typed language; you need to be more specific.
Declaring variables as object just to get your code to compile suggests to me you need to do some more reading on C# fundamentals.
Upvotes: 3
Reputation: 6270
strTimeFrom
is a string (the name of the control I assume) so you can't just cast it into a dropdownlist.
You'll need to get an instance of the control, and since you know it's name you can use FindControl.
var strTimeFrom = (DropDownList)Page.FindControl("ddlTimeFrom" + day);
Upvotes: 8