I have two drop down list.
public void DrpDwn_Cuntry()
{
if (!Page.IsPostBack)
{
MySqlCommand sql_country = new MySqlCommand("SELECT DISTINCT(Country) FROM Animals", cs);
cs.Open();
MySqlDataReader ddlvalue;
ddlvalue = sql_country.ExecuteReader();
ddlcountry.DataSource = ddlvalue;
ddlcountry.DataValueField = "Country";
ddlcountry.DataTextField = "Country";
ddlcountry.DataBind();
ddlcountry.Items.Insert(0, "Choose A Sanctuary");
cs.Close();
cs.Dispose();
}
}
And
public void DrpDwn_Res()
{
if (!Page.IsPostBack)
{
MySqlCommand sql_residents = new MySqlCommand("SELECT DISTINCT(Country) FROM Animals", cs);
cs.Open();
MySqlDataReader ddlvalue_residents;
ddlvalue_residents = sql_residents.ExecuteReader();
ddlcountry_Res.DataSource = ddlvalue_residents;
ddlcountry_Res.DataValueField = "Country";
ddlcountry_Res.DataTextField = "Country";
ddlcountry_Res.DataBind();
ddlcountry_Res.Items.Insert(0, "Choose Your Country");
cs.Close();
cs.Dispose();
}
}
I would like a message box to show if the two selected do not match.
for example if the selected country a from first and country b from second message box shows.
I know i am to use a If Else statement I am just not sure how to write it ?
you can use SelectedItem property of the DropDownList Control to achieve this.
1. get the SelectedItem of the first DropDownList.
2. get the SelectedItem of the second DropDownList.
3. compare both of the SelectedItem values using Equals() method.
4. if the items do not match , display an alert box using javascript as MessageBox is not bydefault avaialble in Webforms (in webforms it is good to use javascript alert) using following Syntax:
Response.Write(#"<script language='javascript'>alert('message here');</script>");
Complete Code: (Code Behind)
Try This:
protected void Button1_Click(object sender, EventArgs e)
{
if (!ddlcountry.SelectedItem.ToString().Equals(ddlcountry_Res.SelectedItem.ToString()))
{
Response.Write(#"<script language='javascript'>alert('Items do not match.');</script>");
}
}
The message box is available in WinForms, the equivalent in WebForms would be the Alert through javascript (You will need to add the reference on jQuery library)
Here it goes:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js "
type="text/javascript"></script>
<script>
function compareAndAlert(){
var value1 = $('#dropDownId').val(); // get the selected value of first dropdown
var value2 = $('#dropDownId2').val(); // get the selected value of second dropdown
if (value1 != value2){
alert("The selected items do not match !"); // If the selected values are not equal display an Alert.
return false;
}
return true;
}
</script>
now call this method on the button click
<asp:Button ID="Button1" onclientclick="javascript:if(compareAndAlert()){}else{return false;}" runat="server" OnClick="Button1_Click" Text="Adopted Pet" Height="31px" Width="150px"/>
Update: This is basically validation and though the Sudhakar's answer is correct but it will lead to unnecessary postback even if the selected values do not match. These type of validations are best served clientside. Do check the update, i have changed the content in onclientclick event of your button
Related
Have a web page that will enroll students, they have to fill their personal information and then it is saved, but when they have to modify it for some reason I set two dropdowns which load all the states and their counties, but the issue is that I dont know how to auto select the same state than the one which is saved in database for each student, Could somebody help me to do that? below is the code I'm working on :
SqlDataReader dr = cmd.ExecuteReader();
DDOWNState.DataTextField = dr["State"].ToString();
DDOWNCounty.DataTextField = dr["County"].ToString();
Just try this
DDOWNState.DataTextField = dr["State"].ToString();
DDOWNState.DataBind();
DDOWNCounty.DataTextField = dr["County"].ToString();
DDOWNCounty.DataBind();
Use the Following code. It will help you.
Whenever you used to bind dataSources(DataTable,DataSet,etc...) into Dropdown or any other server controls you should use the Datasource and Databind property as below.
SqlDataReader dr = cmd.ExecuteReader();
DDOWNState.DataSource=dr;
DDOWNState.DataTextField = dr["State"].ToString();
DDOWNState.DataBind();
DDOWNCounty.DataSource=dr;
DDOWNCounty.DataTextField = dr["County"].ToString();
DDOWNCounty.DataSource();
You Just have to check ether the Student's State is match with your database's State as Shown in code
// Let Say We have Student's Current state is USA
string curruntState = "USA";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (curruntState.ToUpper() == reader["State"].ToString().ToUpper())
{
ListItem item = new ListItem(reader["State"].ToString(), reader["StateID"].ToString());
item.Selected = true;
ddStates.Items.Add(item);
}
else
{
ListItem item = new ListItem(reader["State"].ToString(), reader["StateID"].ToString());
item.Selected = false;
ddStates.Items.Add(item);
}
}
ddStates.DataBind();
reader.Close();
I suppose, you have binded the DropDownList with it's items. Now, you need to do something like this after binding code.
DDOWNState.ClearSelection(); //You need to clear first.
DDOWNState.Items.FindByText(dr["State"].ToString()).Selected = true;
ClearSelection() function needs to be run before selecting any other item in dropdownlist because the dropdownlist allows only one item to be selected at a time. Note that it does not remove items from the dropdownlist, but only clears the selection so that you can select any other ListItem.
You can do the same, if you saved value in database by using FindByValue() function as the same way. This will certainly help you.
For auto select drop-down list which is dependent on other you just need to add
<asp:DropDownList ID-"DropDownList1" runat="server" onSelectedIndexChanged-"DropDownList1 SelectedIndexChanged" AutoPostBack="true">
Set autopostback property="true"
protected void Page_Load(object sender, EventArgs e)
if (DropDownListi.selectedvalue=="1")
{
DropDownList2.selectedValue = "1";
}
EDIT: So I found that this line listItem.Value = rdr["lvl"].ToString(); was adding the same value for each item in the dropdown. Since each text item had the same value, I guess it always defaulted to the first text item. I'm now passing lvl through another query instead of the dropdown. Thanks for all the helpful input!
I'm trying to accomplish a pretty simple task which I've done numerous times before. For some reason, I can't get my dropdown to correctly pass the SelectedItem and SelectedValue.
The SelectedItem and SelectedValue are always returned for the first item in the dropdown, regardless of which item I select.
What am I doing wrong?
Defining dropdown and button:
<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Populating dropdown on PageLoad:
myConnection.Open();
SqlCommand rpt = new SqlCommand(getreports, myConnection);
SqlDataReader rdr = rpt.ExecuteReader();
if (!Page.IsPostBack)
{
while (rdr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = rdr["manager"].ToString();
listItem.Value = rdr["lvl"].ToString();
DropDownList1.Items.Add(listItem);
}
rdr.Close();
myConnection.Close();
}
Code for button click that should pass SelectedItem and SelectedValue:
protected void Button1_Click(object sender, EventArgs e)
{
string user = DropDownList1.SelectedItem.Text;
string lvl = DropDownList1.SelectedValue;
Label1.Text = user;
Label2.Text = lvl;
}
I realized the same value was being assigned for each item. This was the reason the first item in the dropdown kept being passed regardless of the selection. As long as the values are different, all the above code works as expected.
I have two dropdownlists, ddlstates and ddlcitys.
The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?
In code behind, have code that loads the ddlcitys:
protected void ddlstates_TextChanged(object sender, EventArgs e)
{
if (ddlstates.Text != "")
{
List<ListItem> cidades = new List<ListItem>();
SqlConnection conn = new SqlConnection(mytools.stringconection);
SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
cmd.Connection = conn;
dr = cmd.ExecuteReader();
ddlcitys.Items.Clear();
while (dr.Read())
{
cidades.Add(new ListItem(dr[0].ToString()));
}
dr.Close();
conn.Close();
ddlcitys.DataTextField = "Text";
ddlcitys.DataValueField = "Value";
ddlcitys.DataSource = cidades;
ddlcitys.DataBind();
}
}
Asked long time ago, anyway may the answer help anyone.
On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.
hint : make sure that your aspx page enable view state (by default enabled) read more.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//this will called when your page loaded at first time, so bind your drop down values here.
} else {
//this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate).
}
}
I have a dropdownlist which shows a list of countries from my database
public void ShowCountries()
{
OdbcConnection conn;
conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["jConnString"].ConnectionString);
conn.Open();
string sql = "SELECT iso,printable_name FROM country";
OdbcCommand cmd = new OdbcCommand(sql, conn);
try
{
//ddlCountry.DataSourceID = "country";
ddlCountry.DataSource = cmd.ExecuteReader();
ddlCountry.DataTextField = "printable_name";
ddlCountry.DataValueField = "iso";
ddlCountry.DataBind();
}
catch (Exception ex)
{
Check.Text = "3" + ex.Message;
}
finally
{
ddlCountry.Dispose();
conn.Close();
conn.Dispose();
}
}
in the aspx file this is the way how I call this databounded list
<asp:DropDownList ID="ddlCountry" runat="server"
DataTextField="printable_name"
DataValueField="iso">
</asp:DropDownList>
It shows the list but if I want to select an option other then the first one it always inserts the value of the first option en never the selected one, what am I doing wrong ?
It sounds to me like the data source is being (re-)bound to the control before you are accessing the selected value, thus the selected value is always the first value in the datasource.
Where and when does ShowCountries get called? At a guess, I'd say you're missing a check for IsPostback in Page_Load
if (!IsPostback) {
// bind the datasource here, when the page initially loads
ShowCountries();
}
Also, I don't think you want to call Dispose() on ddlCountry in the finally block.
I have one asp.net application, in which i have one dropdown which is binded to dataset. But after selecting one item, the drop down gets cleared all the value, How we can resolve this issue?
This is my dropdown list in design page:
<asp:DropDownList ID="ddlProduct" runat="server" CssClass="textEntry" Width="300px"
AutoPostBack="True" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged">
</asp:DropDownList>
and binding code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindProductDdl();
}
private void BindProductDdl()
{
Products objProducts = new Products();
dsProducts dsProduct = new dsProducts();
ListItem olst = default(ListItem);
olst = new ListItem(" Select", "0");
dsProduct = objProducts.GetDataset("");
ddlProduct.DataSource = dsProduct;
ddlProduct.DataTextField = "Product";
ddlProduct.DataValueField = "Id";
ddlProduct.DataBind();
ddlProduct.Items.Insert(0, olst);
}
protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
{
Products objProducts = new Products();
dsProducts dsProduct = new dsProducts();
string criteria = "";
if (ddlProduct.SelectedItem.Text != " Select")
{
string id = ddlProduct.SelectedItem.Value;
criteria = "Id='" + id + "'";
dsProduct = objProducts.GetDataset(criteria);
productValue = Convert.ToDecimal(dsProduct.tblProducts.Rows[0]["Value"].ToString());
}
}
Thanks in advance..
From your question if I understand correctly you dont want the dropdown list to rebind if it is populated. Also please check your viewstate, this should not be happening, unless you have disabled viewstate
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && ddlProduct.Items.count <=0 )
BindProductDdl();
}
Set the AppendDataBoundItems property of the dropdown to true and this will allow you to have a mix of databound items and non databound items (otherwise that insert statement is clearing your list)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx
Do you have viewstate disabled on the page? Since you are only loading the items into the dropdownlist on the first load of the page, if viewstate is not enabled there will be nothing in the list after the postback.
Not positive, but I've seen in other languages and false interpretation...
You have your product Value as convert of ToDecimal which implies 99.999 for example.
If your ID that you are binding to is based on a whole number (ie: Integer basis), the bound value won't match... even if Value = 1 vs Value = 1.00 it won't match and will not be considered a valid "value" that matches your list. Convert your answer to a whole/integer number and it might do what you expect.
Without seeing the full source for the page I am simply speculating, but have you disabled ViewState on the page? If so, the DropDownList cannot retain its values between postbacks and the lists will have to be reloaded each time.