Setting the selected value to DropDownList in UserControl

Can someone help me with setting the selected DropDownList value to the given database value. I have several TextBox for which it is not difficult to set the value from the database, but what bothers me is DropDownList.

<asp:TextBox ID="txtNaziv" runat="server" Width="430px" Text='<%# DataBinder.Eval(Container, "DataItem.Naziv") %>'></asp:TextBox> 

As far as I know, it is impossible to set the selected value of an element from the code before DropDownList, but I was able to find out something like this (code snippet from the Telerik 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 that I'm using Linq-to-SQL, and I'm not sure how to recreate something like the above code. This is what I have now:

  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"); } 

Another thing I should add is that TextBoxes and DropDownList are inside the UserControl, which is used inside Telerik RadGrid for its EditForm.

Any help would be greatly appreciated.

Thanks!

+4
source share
2 answers

You need to set the SelectedValue drop down menu:

 ddlTOC.SelectedValue = tocValue; 

You can also do it like this:

 ListItem li = ddlTOC.Items.FindByValue(tocValue); if (li != null) li.Selected = true; 

EDIT : The included code to bind the 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(); 
+4
source

Try this one

 ddlTip.Items.FindByValue(tocs).Selected = true; 
0
source

Source: https://habr.com/ru/post/1369493/


All Articles