wolfQueen wolfQueen - 3 months ago 12
ASP.NET (C#) Question

Get the value of dropdown list option to display to text box

I have put the options to a Drop Down list from a database using this code:

if (!IsPostBack)
{pageloaddata.retrievetbldata("Select EmpId, LastName+', '+FirstName+' '+MiddleName AS EmployeeName from Employee");
DropListEmployeeName.DataSource = pageloaddata.SQLTable;
DropListEmployeeName.DataTextField = "EmployeeName";
DropListEmployeeName.DataValueField = "EmpID";
DropListEmployeeName.DataBind();
DropListEmployeeName.Items.Insert(0, "Select")
}


So the Employee Name's value must be their Employee ID (EmpID)

Now what I want to happen is, if the user have selected an employee, the selectedValue(which is the EmpID) must be displayed into a textbox. Here's the little code I create and doesnt work, It may be very easy to others I know please help a beginner here thank you :)

protected void DropListEmployeeName_SelectedIndexChanged(object sender, EventArgs e)
{
string empSelected = DropListEmployeeName.SelectedValue.ToString();
employID.Text = empSelected;
}


Note: the EmpID in the database is actually an int, does it matter if I call it as string? If yes please suggest the best code

Answer

If you want to use Jquery to capture the value of your DropDown when it change take a look at this example I made click here or run the code snippet below.

$(document).ready(function () {

   $("#SelectId").change(function () {
      
      var selectObj = $(this);
      
      $("#inputID").val(selectObj.val());
   
   });

});
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>

<select name="mySelect" id="SelectId">
  <option value="FirstOption">First Option</option>
  <option value="SecondOption">Second Option</option>
  <option value="ThirdOption">Third Option</option>
  <option value="FourthOption">Fourth Option</option>
</select>

<input id="inputID" type="text" name="sampleText" />

</body>

</html>

But if you really want to use the Postback method from your DropDown control try this one.

<asp:DropDownList ID="DropListEmployeeName" runat="server" AutoPostBack="True" 
    onselectedindexchanged="DropListEmployeeName_SelectedIndexChanged">
</asp:DropDownList>