You must Sign In to post a response.
  • Category: ASP.NET

    How to get only first value from DropDownList selected item

    Hi,

    I have loaded the multiple column value in single dropdownlist control. And I want to show the first column value only when i select the dropdownlist item. Below is my code.

    protected void Page_Load(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(strConnString);

    con.Open();
    str = "select * from employee";
    com = new SqlCommand(str, con);
    sqlda = new SqlDataAdapter(com);
    ds = new DataSet();
    sqlda.Fill(ds, "employee");
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
    DropDownList1.Items.Add(ds.Tables[0].Rows[i]["empname"] +"---" + ds.Tables[0].Rows[i]["empaddress"].ToString());
    }
    con.Close();
    }

    When i select the item i want just show the EmployeeName only in dropdown list.
  • #769059
    Hi,

    You can try with the selected values property.
    Please try like the below code and let us know whether it worked.


    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
    DropDownList1.Items.Add(ds.Tables[0].Rows[i]["empname"] +"---" + ds.Tables[0].Rows[i]["empaddress"].ToString());

    DropDownList1.SelectedValue = datagridviewID.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString(); // e is the current selected value

    OR

    DropDownList1.SelectedValue = dataGridView1.CurrentRow.Cell[indexorname].FormattedValue
    }



    Thanks,
    Mani

  • #769061
    Hi,

    As per my understanding you are concatenate 2 or more fields and bind the same to your dropdown, when you are select the item in dropdown you want only one field value rather than all the concatenated fields right?

    If that is the case, in dropdown you are getting the result in string format, simply split the string based on your concatenated object in your case you are concatenated with "---". So, split the string based on that string then it will separate the string whenever "---" string is came and give you the result.

    Ex:

    string result = DropDownList1.SelectedItem.ToString(); // empname---extrastring
    string[] splitresult = result.Split("---"); // now the result would be splitresult[0],splitresult[1]

    You want only empname then use the first index result like splitresult[0]

    Hope this helps you...

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/


  • Sign In to post your comments