How to refresh dropdownlist without reloading the page? - c#

I have two dropdownlists in my page:
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
My code-behind to handle the dropdownlist change is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;
public partial class physicians : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
PopulatePhysician();
}
//PopulateSpecialty();
//PopulateLocation();
}
public void PopulatePhysician() {
SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
//cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Physician's Name";
Item.Value = "0";
//Item.Selected = True
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateSpecialty() {
SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Specialty";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateLocation() {
SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.Items.Clear();
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Location";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
switch(ddlMain.SelectedIndex) {
case 0:
PopulatePhysician();
break;
case 1:
PopulateLocation();
break;
case 2:
PopulateSpecialty();
break;
}
}
}
The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.
How can I achieve it?
UPDATE:
<asp:ScriptManager ID="ScriptManager"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>

Use AJAX. Place both dropdown controls in UpdatePanel and just after the opening Form tag in the page add a ScriptManager (if not already there)

If this is the case, Ajax method should resolve your problem.
Since you are quite new to Ajax, I would describe a bit more details.
There must be only one ScriptManager in the same page.
( If you are using Master page, add to master page and no need to add anymore in nested content page )
Add UpdatePanel and add your controls to ContentTemplate of UpdatePanel.
Add AutoPostBack="True" to your main dropdownlist.
Add SelectedIndexChanged event by double clicking on main dropdownlist.
In SelectedIndexChanged event of main dropdownlist, clear the ddlDrillDown items by adding ddlDrillDown.Items.Clear() method and rebind the data whatever you need based on the value of main dropdown list.

You can use ajax for this goal.
Create asmx-service or webApi controller which return list of items. Call this on change and render it.

As suggested you can use an UpdatePanel. And please do not use ClientIDMode="Static" unless you really, really need to.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ID="ddlMain" runat="server">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<asp:DropDownList ID="ddlDrillDown" name="searchPhys" runat="server">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
Now the problem with UpdatePanel is that it does not refresh the page, but does reload the DOM. So any changes made with jQuery are lost. That is why you lose the DropKick CSS.
You need to trigger $("#ID").dropkick( again. And for that you can use PageRequestManager.
<script type="text/javascript">
$(document).ready(function () {
TriggerDropkick();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
TriggerDropkick();
});
function TriggerDropkick() {
$("#<%= ddlMain.ClientID %>, #<%= ddlDrillDown.ClientID %>").dropkick({
mobile: true
});
}
</script>
Also suggested is using a service to get the values for the DropDownList. This is possible but since this is webforms you would need to disable some validation in order to prevent the Invalid postback or callback argument exception.

Another way you can use is Asp.Net [Webmethod] Attribute.
Create a method with [Webmethod] attribute on your server-side code.
On the front end, use window.PageMethods.(your method name) to invoke the server call.

I used the dependency dropdownlist method. How?:
The contents of DropDownList1_SelectedIndexChanged put in a Sub
For example:
Sub Drop1()
YOURCOD
End Sub
in DropDownList1_SelectedIndexChanged call Drop1()
Create the same for DropDownList2_SelectedIndexChanged (Drop2())
Now in DropDownList1_SelectedIndexChanged call Drop1 and Drop2.
That's it.

Related

How to enable the dropdown list on a specific radio button

I am trying to enable the dropdown list when the user select the radio button with a id =9, for some reason the jquery function is not working
For debugging purpose, i've tried to alert the selected id but it's null
Any thoughs?
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT * FROM case_cat_lv1";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
rblFruits.DataSource = cmd.ExecuteReader();
rblFruits.DataTextField = "category_name";
rblFruits.DataValueField = "id";
rblFruits.DataBind();
con.Close();
}
}
}
}
ASP.NET .aspx
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="rblFruits" runat="server" OnCheckedChanged="air_CheckedChanged" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
$('#rblFruits').change(function () {
alert($(this).val());
if ($(this).val() == '9') {
$('.dropdown').attr("disabled", false);
}
else {
$('.dropdown').attr("disabled", true);
}
//alert($(this).val());
});
});</script>
</form>
Try $(this).find(":checked").val(); instead of $(this).val(). And if you want id of selected radio button then $(this).find(":checked").attr("id").
To enable dropdown list you can remove attribute disabled. It should work.
$('.dropdown').removeAttr("disabled");
For disabling your code will work fine.
$('.dropdown').attr("disabled", true);
A few of things to consider. ASP.net webforms can mangle ids, RadioButtonList is not an HTML entity and is rendered as radio buttons with their own ids and values, finally you also have OnCheckedChanged="air_CheckedChanged" as a server side event handler which could be causing you problems.
With these kinds of issues with .net WebForms, always check the rendered HTML to see if it is what you were expecting.
Here's how I'd do it:
<form id="form1" runat="server">
<div>
<!-- I've taken out the server side event handler -->
<asp:RadioButtonList ID="rblFruits" runat="server" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
/*#rblFruits will be a container, not actual radio buttons*/
/*Keeping in mind name mangling, get the actual client ID.
Note that if you're putting thing in an external js file,
you'll need to come up with another plan*/
$('#<%=rblFruits.ClientID%> input[type=radio]').change(function () {
alert($(this).val());
$('.dropdown').prop("disabled", $(this.val() !== '9'));
});
});</script>
</form>
See also: http://api.jquery.com/prop/

Stopping user entering numerical value in a texbox when using C#

I am trying to stop the user to enter a numerical value in the search criteria text box when the Dropdown value is MBID The code works I only need help on how to resolve the validation issue
C# Code
protected bool searchData()
{
string val = DropDownList1.SelectedItem.Value;
switch (val)
{
case "MBID":
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT count(*)
from Patient where MBID = #SearchCriteria ", con))
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
int userCount = (Int32)cmd.ExecuteScalar();
da.Fill(dt);
}
}
}
}
The Search button call the code below
protected void btnSearch_Click(object sender, EventArgs e)
{
if (FormValidation()) if (searchData())
{
BindGrid();
inputUpdateFornData();
}
}
HTML Code
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="MBID">MBID</asp:ListItem>
<asp:ListItem Value="HPNumber">HP Number</asp:ListItem>
<asp:ListItem Value="NHSNumber">NHS Number</asp:ListItem>
I cannot used the code below because numerical value can be entered for the other option of the dropdown
<asp:TextBox ID="txtSearchCriteria" runat="server />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtSearchCriteria" Type="Integer"
Operator="DataTypeCheck" ErrorMessage="Value must be an integer!" />
This is how to do it:
try
{
int d = int.Parse(txtSearchCriteria.Text);
//if works str is a number
}
catch (Exception e)
{
Console.WriteLine("It isn't a number!");
}
Add ClientValidationFunction="validateFunction" in your CompareValidator.
And write validation function as follows-
function validateFunction(s,args){
if (yourdropdown.value == "MBID")
{
// Your code
}
}
If you want server validation , add OnServerValidate attribute and handler function on server side.
hello please try below code for javascript validation
below is javascript code
<script>
function validateSearch()
{
var dropdown = document.getElementById("<%= ddlSearch.ClientID %>");
var txtSearch = document.getElementById("<%= txtSearch.ClientID %>");
if (dropdown.value == "MBID")
{
var reg = /^\d+$/;
if (!reg.test(txtSearch.value)) {
alert("Please enter proper value");
txtSearch.focus();
return false;
}
}
}
</script>
and below is aspx code of dropdown and textbox.
<asp:DropDownList runat="server" ID="ddlSearch">
<asp:ListItem Text="Select" Value="-1"></asp:ListItem>
<asp:ListItem Text="MBID" Value="MBID"></asp:ListItem>
<asp:ListItem Text="Name" Value="Name"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:Button runat="server" ID="btnSearch" Text="Search" OnClientClick="return validateSearch();" />

Where should I put new ListItem for DropDownList

I have a page with 1 main DropDownList and 2 other. Made it to choose settings for printing report.
The problem is - I use DataSources in these DropDownLists but they haven't an empty value. Where should I put adding a new empty value into DropDownList for correct work?
There is my code (in a comment is a thing that i need to add)
protected void ddlMain_Load(object sender, EventArgs e)
{
switch (ddlMain.SelectedValue)
{
case "1":
dFirst.Visible = true;
dSecond.Visible = false;
break;
case "2":
dFirst.Visible = false;
dSecond.Visible = true;
break;
}
<div>
<asp:DropDownList ID="ddlMain" runat="server" AutoPostBack="true" OnLoad="ddlMain_Load">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2 " Value="2"></asp:ListItem>
</asp:DropDownList>
</div>
<div runat="server" id="dFirst" visible="false">
<asp:DropDownList ID="ddlFirst" runat="server" DataSourceID="sdsFirst"
DataTextField="name" DataValueField="id" OnLoad="ddlFirst_Load">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsFirst" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>">
</asp:SqlDataSource>
</div>
//ddlFirst.Items.Add(new ListItem("--Select--", "-1"));
I tried OnLoad secondary element, OnLoad main DropDownList and Page_Load. They don't fit me because new ListItem don't appears when page firstly loading or added more than 1 time when page refreshes.
Use Insert method in page load.
ddlAcademicYear.Items.Insert(0, new ListItem("-- Select --", "-1"));
0 is position at which you want to insert.
Add an optionlabel to your dropdownlist and assign the text "--Select--". Your dropdownlist should now have the desired default value.

SelectIndex_changed not worling in Asp.net for selecting values

i am new on .net development now i am facing the problem but i do not know what the solution for this
i am creating the dropdown list and bind it with data but when i select the any data from list it does not changes the textbox with the related value but when i click on button it goes inside the code means goes on debuging from where i mark the debug cursor
here is my code behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCardCode = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=testing;Initial Catalog=testdb;Persist Security Info=True;User ID=abcd;Password=asdfg");
using (connection)
{
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName,T3.CntctCode,T3.Name FROM OCRD T1 inner join OCPR T3 on T1.CardCode=T3.CardCode where T3.CardCode=#CardCode ", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selectedCardCode);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.DropDownList1.SelectedItem.Value = selectedCardCode;
}
connection.Close();
}
}
and here is my method cardcode
protected void LoadOptionsCardCodeTable()
{
DataTable CardCode = new DataTable();
string id, name, newName;
SqlConnection connection = new SqlConnection("Data Source=abc;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=asdf;Password=asdfgh");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName from ocrd T1 ", connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = name + " ---- " + id;
DropDownList1.Items.Add(new ListItem(newName, id));
}
}
}
}
here is my design code
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
</form>
Kindly help your help will be higly appreciatable
Set AutoPostBack property to true for your dropdownlist.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
By default, asp.net server controls like dropdownlist, textbox have their respective events as cached which means it registers the event but does not fire untill an actual postback happens. In you case when you are clicking the button a postback is happening and the cached event of your dropdwonlist is also getting executed.
To force postback from your dropdown you will have to set the PostBack property to true.
You have to set AutoPostBack="true" in order to trigger the event:
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Notes:
A postback is initiated by the browser, and reloads the whole page, according to an event.if any changes(here onselectedindexchanged) we made in the control result in a postback then that are called AutoPostBack.All controls except, Buttons, Hyperlinks and LinkButtons have a default AutoPostBack property of false, we have an option to make them true if needed.
Set AutoPostBack="true" Otherwise DropDownList1_SelectedIndexChanged doesn't fire.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

Dropdown SelectedItem changes

I have two dropdown , the items in the second drop down solely depends on the selected item from the first dropdown. So therefore i want the second dropdows item changes on item selection from the first dropdown. My first drop down is as follows
<td>
<asp:DropDownList ID="DropClient" runat="server" style="margin-left: 0px" AutoPostBack="true" Width="200px" OnTextChanged="DropClient_TextChanged">
</asp:DropDownList> </td>
<td>
I wanted to use onselectedindexchanged previously , but it does not fires as required. Therefore i put my method in the onTextChanged events as below.
protected void DropClient_TextChanged(object sender, EventArgs e)
{
bindDrEmail();
}
and my bindEmail();
connection.Open();
string sql = "SELECT a.clientID,a.cname,c.name FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID JOIN [CONTACT] c ON b.bid=c.bid WHERE a.cname =#clientname";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#clientname", DropClient.SelectedItem.Text);
SqlDataReader reader = cmd.ExecuteReader();
drEmail.Enabled = true;
drEmail.DataSource = reader;
drEmail.DataTextField = "name";
drEmail.DataValueField = "clientID";
drEmail.DataBind();
reader.Dispose();
reader.Close();
connection.Close();
the above works as expected, but after i select an item in the second dropdown, it does not submit the selected item as chosen . It rather submit the first item in the list by default. Also when i click the submit button, it quickly refresh and submit the first item in the list. I am confused, any help would be appreciated.
Why don't you use onSeletedIndexChanged event, call same function on onSeletedIndexChanged event, may be it will be helpful for you
OnSelectedIndexChanged="cboRegion_SelectedIndexChanged"
Place the code to bind the first dropdown inside the !IsPostBack check
if (!Page.IsPostBack)
{
//Bind your first dropdown here
}
The page load gets triggered everytime a postback happens so to prevent your code loading everytime and resetting your dropdownlists do the following:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Put your code in here. This will only load the first time the page loads.
bindDrEmail();
}
}
You can use Update Panel .
This is example code ,
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Value="0">Choose...</asp:ListItem>
<asp:ListItem Value="1">test1</asp:ListItem>
<asp:ListItem Value="2">Test2</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
Guys thank all for your time. I finally figured out the problem. First the reson why it does not fires the events previously was because i set the second Dropdown "AutoPostback" as true, and didn't set the same for the first DropDown which i want to fires. When i reverse this process it fires as below.
<asp:DropDownList ID="DropDownClient" runat="server" style="margin-left: 0px" AutoPostBack="true"
Width="200px" onselectedindexchanged="DropDownClient_SelectedIndexChanged">
</asp:DropDownList>
And
<asp:DropDownList ID="drContact" runat="server" style="margin-left: 0px" Width="200px"> </asp:DropDownList>
Now it fires. Second the very reason why the selecteditem from the second Dropdown changes quickly on button click and submit the first item instead, was because of the dataValueField of the second DropDown. My convine the two tables as follows.
string sql = "SELECT a.clientID,a.cname,c.contactID,c.name FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID JOIN [CONTACT] c ON b.bid=c.bid WHERE a.cname =#clientname";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#clientname", DropDownClient.SelectedItem.Text);
SqlDataReader reader = cmd.ExecuteReader();
drContact.Enabled = true;
drContact.DataSource = reader;
drContact.DataTextField = "name";
drContact.DataValueField = "clientID";
drContact.DataBind();
Notice the drContact.DataValueField is set as "clientID" . And clientID and the drContact.DataTextField are from different tables. The column i required is "name" and therefore have to change the drContact.DataValueField to the primary key of the table where name is a column. And therefore.
drContact.Enabled = true;
drContact.DataSource = reader;
drContact.DataTextField = "name";
drContact.DataValueField = "contactID";
drContact.DataBind();
The above works fine for me. Thanks for your time.

Categories

Resources