Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set radcombobox selected value from database?

I have noticed a big difference between the stock Dropdownlist and RadComboBox. With the asp:dropdownlist it is easy to set the selected value from a database record. But when I try to do that with RadComboBox, it doesn't work. Even when I try rcboTest.Text = "Thomas Hardy", the RadComboBox won't change at all.

I'm using VS2012, Sql Server 2012, RadComboBox and using NorthWind as the database.

Here is the code to populate my DataTable

public DataTable NWDContacts()
    {
        DataTable dt = new DataTable();

        string strCm = "Select * from [Contacts]";
        SqlCommand cm = new SqlCommand(strCm, cn);
        cm.CommandType = CommandType.Text;

        SqlDataAdapter da = new SqlDataAdapter(cm);

        cn.Open();
        da.Fill(dt);
        cn.Close();

        return dt;
    }

here is my codebehind to populate the RadComboBox

protected void Button1_Click(object sender, EventArgs e)
    {
        rcboTest.DataSource = DA.NWDContacts();
        rcboTest.DataTextField = "ContactName";
        rcboTest.DataValueField = "ContactID";
        rcboTest.DataBind();
    }

now here is the button click event I am using to try to change the RadComboBox.Text

protected void Button2_Click(object sender, EventArgs e)
    {
        rcboTest.Text = "Thomas Hardy";
    }

I have tried using rcboTest.SelectedValue, rcboTest.SelectedItem, and rcboTest.Text and the combobox doesn't want to show the Text and the SelectedValue and SelectedItem, throws an error saying that it is only read only.

So in short, I want to populate my RadComboBox (which I can ) and when I go to update a record I need to be able to set the RadComboBox Text to the database value.

I know the code I am showing is contradicting what I want to do, but it is for testing before I put it to a live app.

like image 449
Chris Avatar asked Jun 14 '14 16:06

Chris


1 Answers

There are ways to do this -

RadComboBoxItem item = RadComboBox1.FindItemByText("Thomas Hardy");
item.Selected = true;

int index = RadComboBox1.FindItemIndexByValue("2");
RadComboBox1.SelectedIndex = index;

//In your case value will be ContactID
RadComboBox1.SelectedValue = value;

Reference - http://www.telerik.com/help/aspnet-ajax/combobox-items-server-side-code.html

like image 79
Typist Avatar answered Oct 30 '22 05:10

Typist