Get selected value from dropdownlist in asp.net - c#

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.

Related

Drop down list not updated when data changed

I have a drop down list of categories that is databound. The selection from this populates a gridview. When I delete a category, it is successfully updating my gridview of products (showing no entries), but not he dropdownlist of categories until I re-run the program.
My page load:
protected void Page_Load(object sender, EventArgs e)
{
// Check if loaded for first time.
if (!IsPostBack)
{
// Bind the data displayed in the Dropdownlists.
Login.SelectAllCat(DropListCat);
}
}
My code to delete a category:
protected void BtnDeleteCat_Click(object sender, EventArgs e)
{
try
{
// Get int id from selectioin in drop down list.
int id = Convert.ToInt32(DropListCat.SelectedValue.ToString());
// Call method to open data base, create command from stored procedure and delete item to database.
Login.DeleteCategory(id);
// Update the data displayed in the Dropdownlists.
Login.SelectAllCat(DropListCat);
}
catch (NullReferenceException)
{
LblProdId.Text = "No Category Selected!";
}
}
My dropdownlist:
<asp:DropDownList ID="DropListCat" runat="server" BackColor="#66FFFF"
Width="200px" AutoPostBack="True" AppendDataBoundItems="True">
</asp:DropDownList>
My connection and binding code. In Login class.
// Method to select all categories and display them in dropdown lists.
public static void SelectAllCat(DropDownList list)
{
// SqlConnection.
SqlConnection con = new SqlConnection(conString);
// Create new command and parameterise.
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SelectAllCat";
//
// Adapted from
// Source link: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/data-binding-to-dropdownlist-and-listbox-in-Asp-Net/
//
cmd.Connection = con;
try
{
// Open connection and bind data to GUI.
con.Open();
list.DataSource = cmd.ExecuteReader();
list.DataTextField = "CatName";
list.DataValueField = "CatID";
list.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
My stored procedure:
CREATE PROCEDURE SelectAllProd
AS
SELECT * FROM Prod;
GO
This is the result after I have attempted to delete a category.
When I re-run the project, the category will have been deleted.
Edit
Actually, it is deleting the category, but it's retaining the original data binding from page load. So I guess I need to work out how to wipe that.
Write
DropListCat.DataBind();
in BtnDeleteCat_Click
I fixed it by clearing the drop down list items before re-binding the data, as so:
// Method to select all categories and display them in dropdown lists.
public static void SelectAllCat(DropDownList list)
{
// Clear any previously bound items.
list.Items.Clear();
// etc.../

Handling "Dropdown does not contain selected item" Error

I am having trouble with a particular situation. The values in my dropdownlist are as follows: 101, 102, 103, but at any point in time the use can add or deactivate items to the dropdown ex: 101, 104, 106.
I have this dropdownlist embedded into a listview edit item template. So if the user adds a record with value 102, then later on deletes this value they cannot edit this value because I get the above error.
So what I am trying to figure out is how I can handle this message to let the use know they cannot edit the record. What I have so far is the ListView_ItemEditing event handler:
protected void LV_Equipment_ItemEditing(object sender, ListViewEditEventArgs e)
{
LV_Equipment.EditIndex = e.NewEditIndex;
e.Cancel = true;
try
{
LV_Equipment.DataBind();
}
catch (Exception ex)
{
//This is telling the user they cannot edit the record.
AlertMessage("you cannot edit this record.");
}
DropDownList UnitIDDDL = (DropDownList)(LV_Equipment.EditItem.FindControl("DropDownList1"));
DropDownList DriverIDDDL = (DropDownList)(LV_Equipment.EditItem.FindControl("DDL_Insert_Drivers"));
//We need to get the driver for the selected unit in the listview.
int ID = DatabaseInteraction.GetUnitDriver(UnitIDDDL.SelectedValue);
//Now that we have the id we can set the ddl.
DriverIDDDL.SelectedValue = ID.ToString();
DriverIDDDL.DataBind();
}
So if the user tries to edit a valid item there is no problem. But if they try to edit a deactivated item from the listview they LV_Equipment.DataBind() method will fail, and the rest of the code will throw an error as the UnitIDDDL and DriverIDDDL are set as null.
Any ideas on how to make this workaround effective?
Ok, here's what you need to do.
Your data binding should be coming from a SQL query of some sort. Let's assume it looks something like this:
string query = "SELECT ItemNumber FROM TableName";
SqlConnection conn;
SqlDataAdapter da = new SqlDataAdapter(query,conn);
DataTable sqlTable = new DataTable("Test");
da.Fill(sqlTable);
LV_Equipment.DataSource = sqlTable;
What you'll want to do is change your query so that it looks something like this:
string query = "SELECT ItemNumber FROM TableName WHERE Active = 'True'";
That should solve your problem.
Add a return to your catch block:
try
{
LV_Equipment.DataBind();
}
catch (Exception ex)
{
//This is telling the user they cannot edit the record.
AlertMessage("you cannot edit this record.");
return; // don't continue to process
}

How to store values before postback

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).
}
}

If statement between two drop down list. C#

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

Transfer data to another table and make previous GridView empty

I have GridView. When I click a button, it sends data to another table and makes the previous GridView empty.
I have the following code for the button click, but it does not make the previous GridView empty.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string userApply = "insert into Company (CompanyName) select (JobTitle) from Jobs where JobTitle=JobTitle";
SqlCommand insertApply = new SqlCommand(userApply, conn);
try
{
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("ApplyJob.aspx");
}
catch (Exception er)
{
Response.Write(er.ToString());
}
finally
{
}
}
}
}
Are you clearing the previous gridview anywhere?
Maybe try this before your redirect:
grvPrevious.DataSource = null;
grvPrevious.DataBind();
it looks like you have your GridView in ApplyJob.aspx, since you are redirecting to that page in your try block and there you see the gridview holding some values. You may pass a query string along with ApplyJob.aspx and then in your form load of ApplyJob.aspx check for that query string. If you find the value then clear the Gridview. Something on the following line..
In your try block do :
Response.Redirect("ApplyJob.aspx?ClearGridView=YES");
In your Form_Load event of the ApplyJob.aspx check for the query string
if(Request.QueryString["ClearGridView"] != null && Request.QueryString["ClearGridView"] =="YES")
{
yourGridView.DataSource = null;
youGridView.DataBind();
}

Categories

Resources