Reputation: 3710
Could someone help me with setting the selected value of the DropDownList to the database given value. I have couple of TextBoxes for which it isn't hard to set the value from the database, but what drives me crazy is DropDownList.
<asp:TextBox ID="txtNaziv" runat="server" Width="430px" Text='<%# DataBinder.Eval(Container, "DataItem.Naziv") %>'></asp:TextBox>
As far as I know, it isn't possible to set the selected item value from the code front to the DropDownList, but I was able to find out something like this (code snippet from Telerik's RadGrid documentation):
protected void EmployeeDetails_DataBinding(object sender, System.EventArgs e)
{
ArrayList tocs = new ArrayList(new string[] { "Dr.", "Mr.", "Mrs.", "Ms." });
ddlTOC.DataSource = tocs;
ddlTOC.DataBind();
object tocValue = DataBinder.Eval(DataItem, "TitleOfCourtesy");
if (tocValue == DBNull.Value)
{
tocValue = "Mrs.";
}
ddlTOC.SelectedIndex = tocs.IndexOf((string)tocValue);
ddlTOC.DataSource = null;
}
The problem is I'm using Linq-to-SQL and I'm not sure how to recreate something like the above code. This is what I currently have:
protected void ddlTip_DataBinding(object sender, EventArgs e)
{
TSEntities db = new TSEntities();
var partType = (from pt in db.PartType
select new { pt.idPartType, pt.Naziv }).ToArray();
ddlTip.DataSource = partType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
object Tip = DataBinder.Eval(DataItem, "idPartType");
}
One more thing I have to add that this TextBoxes and DropDownList are inside the UserControl which is being used inside Telerik's RadGrid for its EditForm.
Any help would be appreciated.
Thank you!
Upvotes: 4
Views: 4277
Reputation: 46047
You need to set the SelectedValue of the dropdown:
ddlTOC.SelectedValue = tocValue;
You can also do it like this:
ListItem li = ddlTOC.Items.FindByValue(tocValue);
if (li != null)
li.Selected = true;
EDIT: Included code to bind list directly to db.PartType:
TSEntities db = new TSEntities();
ddlTip.DataSource = db.PartType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
ddlTip.SelectedValue = DataBinder.Eval(DataItem, "idPartType").ToString();
Upvotes: 4