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>
Related
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();" />
I am programming in ASP.NET, visual studio. I have a dropdown list created in HTML form. If I dropdown the list, it displays the record from associated column in the table. But what I want is to show the corresponding value / record with that list item.
For example in the table, I have column id, productname and price. After choosing a particular product name (from drop down list), the associated price with it must be displayed in front of it (in a label).
However, By default, I want the drop down list to shows nothing in the beginning.
UPDATE:
Store.aspx:
<form id="form1" runat="server">
<div>
Welcome
<asp:Label ID="Label3" runat="server" ></asp:Label>
<br />
<br />
Products: <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [productdata]"></asp:SqlDataSource>
Price:
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Cart" />
<br />
<br />
Items in cart: <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<br />
<br />
Total Price: <asp:Label ID="Label2" runat="server"></asp:Label>
</div>
</form>
Store.aspx.cs:
public partial class Store : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
if (!IsPostBack)
{
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlDataReader rd;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata where id=" + Convert.ToUInt32(DropDownList1.SelectedValue), sc);
sc.Open();
rd = sqlcom.ExecuteReader();
if (rd.Read())
{
Label1.Text = rd[2].ToString();
}
sc.Close();
}
}
}
Database:
CREATE TABLE [dbo].[productdata] (
[Id] INT NOT NULL,
[productname] VARCHAR (50) NULL,
[price] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
This Edit according to using AutoPostBack=True and if (!IsPostBack) in Page_Load thanks to Arindam:
For simply solution using postback event:
First you should add OnSelectedIndexChanged event for dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="GetPrice" AutoPostBack="true">
</asp:DropDownList>
Then in code behind you just get selected value and fill to the label price
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void GetPrice(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
You have to use AutoPostBack=True so that when you change index of dropdownlist, it will trigger a postback to server so the function GetPrice(...) will be called.
Every time the page postback, it will call function Page_Load(...) first, so you must use propertive IsPostBack to check if case1_this is the first time the page is loaded, or case2_a postback event, and you only set the ddl datasource at case1 because if you set datasource, by default the dropdownlist will reset to select first item in list.
When you go advance, you should consider using Javascript and Jquery to solve this, so the page will not load again like this postback solution.
And one more thing, you should name your controls well, don't make them default like that. It's one of two hard things in programming.
Yes you can but if not please use datatable and i am sure that work fine .if u not able do that just post I will give the correction.
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.
I want to bind a Hidden Field because I want to pass a value from code behind to the asp:Parameter Name="HOME_TEAM_COACH_ID" Type="Int32".
My asp:
<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdating" >
<EditItemTemplate>
HOME_TEAM:
<asp:DropDownList ID="DropDownListHometeam" runat="server"
DataSourceID="SqlDataGetTeams"
DataTextField="NAME" DataValueField="ID" SelectedValue='<%# Bind("HOME_TEAM_ID") %>'>
</asp:DropDownList>
<asp:HiddenField runat="server" ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>' />
</EditItemTemplate>
And c# behind is:
protected void FormView1_ItemUpdating(object sender, FormViewUpdatedEventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
DropDownList HomeTeamId = FormView1.FindControl("DropDownListHometeam") as DropDownList;
string team = string.Format("{0}", HomeTeamId.Text);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BasketballConnectionString1"].ToString());
conn.Open();
string queryHome = "SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")";
SqlCommand cmd = new SqlCommand(queryHome, conn);
var Home_Coach_Id = cmd.ExecuteScalar().ToString();
HiddenField HomeCoachIdLabel = FormView1.FindControl("testLabel") as HiddenField;
HomeCoachIdLabel.Value = Convert.ToString(Home_Coach_Id);
conn.Close();
I want Help with the last four lines where I want to pass the Home_Coach_Id value to bind the asp:HiddenField ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>'.
When I click update, it doesn't change the value in database. (When I debug, in the last lines it gives me the correct HomeCoachIdLabel.Value.)
any suggestions?
You do not need the explicitly set the HiddenField's Value property, because it is done by the <%# Bind("HOME_TEAM_COACH_ID") %> in your markup.
I believe your problem is that you are not returning the HOME_TEAM_COACH_ID from your query to the database in your SELECT statement:
SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH
INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID
WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")
The problem is that it needs the method prerender and not the method onitemupdated.
asp:FormView ID="FormView1" runat="server" OnPreRender="FormView1_OnPreRender" >
and also in c#
protected void FormView1_OnPreRender(object sender, FormViewUpdatedEventArgs e)
{
It also works when I put it in page load{ }.
The next step is to make the insert event....
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.