How to auto select in dropdown asp.net - c#

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";
}

Related

Keeping ViewState of page after PostBack Refresh

I have a drop down list with the list items created in the code behind. ddlFill(). Pretty simple and does the job. It's populated with the current month and some months ahead. I use this drop down as a selection to fill a Gridview. When this drop down index changes, it changes a hidden field value and a corresponding query to fill the gridview. All this works as it should. Within the gridview I have another dropdown list and a button. Both submit the selected row to a database. That also works fine. The problem is, each time one of these rows submits to the database, it causes a post back and it resets the whole page. It resets the drop down list to the first list item . I.E. I change the drop down list to index 4 for example. Which would be April in this case. If I submit a row to the db, the page refreshes and goes back to index 0 .. January in this case. How do I keep it from resetting this way and maintaining the position I was in when I submitted the row?
I have tried a few different options. I've tried session states. hidden field value changes. Nothing seems to work. It either does not perform the post back therefore never submits to the db or it does the post back, submits correctly, then resets the whole page. Including resetting the hiddenfield value back to 0
/* This is up in Page load. */
if (Session["pageStatus"] != null)
{
if (Session["pageStatus"].ToString() == "Loaded")
{
hf2.Value = "Loaded";
}
}
else
{
hf2.Value = "New";
}
if (Session["selectedMonth"] != null)
{
hf1.Value = Session["selectedMonth"].ToString();
}
if (ViewState["button_was_clicked"] != null)
{
ddlFill();
StyleDDL();
}
lblTestlabel.Text = hf2.Value;
AddAttributes();
ShowMonth();
if (!Page.IsPostBack)
{
btnReviewCurrentMonth_OnClick(sender, e);
ddlFill();
StyleDDL();
}
private void ddlFill()
{
string a, b, c, d, e, f;
a = "0";
b = "1";
c = "2";
d = "3";
e = "4";
f = "5";
DropDownList1.Items.Insert(0, new ListItem(ReturnMonth(a))); // A blank object call and the ReturnMonth Method fill the list items.
DropDownList1.Items.Insert(1, new ListItem(ReturnMonth(b)));
DropDownList1.Items.Insert(2, new ListItem(ReturnMonth(c)));
DropDownList1.Items.Insert(3, new ListItem(ReturnMonth(d)));
DropDownList1.Items.Insert(4, new ListItem(ReturnMonth(e)));
DropDownList1.Items.Insert(5, new ListItem(ReturnMonth(f)));
/* These were for various testing options to get it to maintain the
state */
hf2.Value = "Loaded";
Session["pageStatus"] = "Loaded";
DropDownList1.SelectedIndex = Int32.Parse(hf1.Value);
}
My goal is to maintain the state of the page after the submission to the db occurs.
I found this question difficult to ask because it had so many moving parts. The ddlFill() method wasn't the problem. All it litterally did was fill list items. Those corresponding Selected Index values would change when selected and based on those values I would assign a different value to a hidden field. Which was then used as SqlDataSource control variable and would bring back GridView data based on that control value.
A drop down list within the gridview was used to select and submit the indexed row to a SQL DB. At the end of that code I was refreshing the page. It needed a refresh to properly submit and bring back a fresh Gridview with the previously submitted row now gone. That was the problem. When it refreshed, it changed the hidden field value to 0 and reset everything back. So, here is what I did.
//This method controls the Drop Down List change event. Underwriter change.
protected void DropDownList1_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int idx = row.RowIndex;
GridView1.SelectedIndex = idx;
string Client = GridView1.SelectedRow.Cells[0].Text;//Client Name
string NewUw = ddl.Text.ToString();
int UniqCNT = new Int32();
UniqCNT = Int32.Parse(GridView1.SelectedRow.Cells[1].Text.ToString()); //UniqClient */
string ExpPolicyNums = GridView1.SelectedRow.Cells[2].Text;
int Ub = Int32.Parse(GridView1.SelectedRow.Cells[10].Text);//UniqBroker
DateTime ExperationDate = DateTime.Parse(GridView1.SelectedRow.Cells[6].Text); //ExpDate
string Company = GridView1.SelectedRow.Cells[7].Text; //Company issuer
string Broker = GridView1.SelectedRow.Cells[8].Text; //Broker_Name
string Premium = GridView1.SelectedRow.Cells[3].Text; //Premiums
string TotalPremium = GridView1.SelectedRow.Cells[4].Text; //Total premiums
string Reviewed = "No"; //Updates the DB and shows that it hasn't been reviewed by the Message Creator
//DateCreated gets inserted when record is created
string InsertedBy = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1);
DateTime dateUpDated = DateTime.Now; //Inserts a dateUpdated record
string query = "INSERT INTO [GTU_Apps].[dbo].[Reviewed_Renewal_Policy] (UniqClient, Client, [Expiring_Policies], Premiums, TotalPremium, UniqBroker, ExpDate, NewUw, Company, Broker_Name, Reviewed, DateUpDated, InsertedBy) " +
"VALUES (#UniqCNT, #Client, #ExpPolicyNums, #Premium, #TotalPremium, #Ub, #ExperationDate, #NewUw, #Company, #Broker, #Reviewed, #dateUpDated, #InsertedBy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=GTU_Apps;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqCNT", UniqCNT);
comm.Parameters.AddWithValue("#Client", Client);
comm.Parameters.AddWithValue("#ExpPolicyNums", ExpPolicyNums);
comm.Parameters.AddWithValue("#Premium", Premium);
comm.Parameters.AddWithValue("#TotalPremium", TotalPremium);
comm.Parameters.AddWithValue("#Ub", Ub);
comm.Parameters.AddWithValue("#ExperationDate", ExperationDate);
comm.Parameters.AddWithValue("#NewUw", NewUw);
comm.Parameters.AddWithValue("#Company", Company);
comm.Parameters.AddWithValue("#Broker", Broker);
comm.Parameters.AddWithValue("#Reviewed", Reviewed);
comm.Parameters.AddWithValue("#dateUpDated", dateUpDated);
comm.Parameters.AddWithValue("#InsertedBy", InsertedBy);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
GridView1.DataBind();
GridView1.SelectedIndex = -1;
int index = DropDownList1.SelectedIndex;
ConfirmIndex(index);
//End(sender, e);
}
Using the DataBind worked. It only refreshed the Gridview. Which was really what I needed. I had other items that were refreshing too. That's why those calls below it are there. If someone sees this, hopefully it will help.

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

ASP dynamic DropDownList selected index

My web form starts out as two TextBoxes, two Buttons, a CheckBoxList (bound to the results of a database query), and an empty DropDownList.
When the user enters a search phrase into the first TextBox and hits enter (or clicks the first Button, "Search"), a GridView appears, populated with rows pulled from the database. When the user hits the Select button on one of the rows, the DropDownList is populated (bound to results of a database query) and enabled (if the query returned results -- if there were no results, it remains disabled). When the second Button ("Save Settings") is clicked, the relevant data is saved to the DB, the GridView's selection is cleared, and the DropDownList is cleared and disabled.
All of the above works. The problem comes from the DropDownList. I can't get the C# code to recognize the changing SelectedIndex; depending on how I shuffle my code around, the index is always either 0 (and the DropDownList is forced to stay on the first item), or -1 (and the list becomes disabled).
DropDownList code:
<asp:DropDownList ID="myList" runat="server" AutoPostBack="True"
DataTextField="MyName" DataValueField="MyID"
Enabled="False" onselectedindexchanged="myList_SelectedIndexChanged" />
C# code:
protected void myGrid_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
if (myGrid.SelectedIndex >= 0)
{
int id = int.Parse(myGrid.Rows[myGrid.SelectedIndex].Cells[2].Text);
connection.Open();
string query = "..."; // Omitted for brevity; the query is correct
SqlDataSource source = new SqlDataSource(connectionString, query);
source.SelectParameters.Add("Param1", TypeCode.String, id.ToString());
DataTable dt = ((DataView)source.Select(DataSourceSelectArguments.Empty)).Table;
dt.AcceptChanges();
myList.DataSource = dt;
myList.DataBind();
myList.Enabled = myList.Items.Count != 0;
if (!myList.Enabled)
{
myList.Items.Add(new ListItem("No Results", "0"));
}
}
}
}
protected void myList_SelectedIndexChanged(object sender, EventArgs e)
{
// ((DropDownList)sender).SelectedIndex == -1
}
I've read that there are some problems with DropDownList while searching for a solution to my problem, but besides the note to set AutoPostBack="True", none of the other situations I've found have helped.
One common reason on why the DropDownList loses its SelectedIndex value is, that during the postback is binded again with data. Do you populate data to the DropDownList somewhere else in your code? Maybe there is something else that causes the SelectedIndex event of the GridView to fire again?
Another thought is that changing the Enabled status of the DropDownList might cause this behavior. Try your code without disabling the DropDownList, and see if something changes.

How can I use the selected rows in GridView as a source for a GridView in another page?

I am writing a web site in Visual Studio, something like an on-line library. I have a GridView on the first page that presents all of the books available from the data source and some other properties also contained in the data source. The GridView contains check boxes and the user can choose which books he wants to order by checking a box. My question is how can I use the data in the selected rows, the list of books with their properties and show that list on another page, so that the user is able to know which items he has selected?
I tried with a for loop on the FirstPage:
protected void Page_Load(object sender, EventArgs e)
{
List<int> ids = new List<int>();
if (!IsPostBack)
{
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int bookID = (int)GridView1.DataKeys[i][0];
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");
if (cb.Checked)
{
ids.Add(bookID);
}
}
Session["Ids"] = ids;
Response.Redirect("SecondPage.aspx");
}
}
and on the SecondPage:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtBooks = new DataTable("Books");
dtBooks.Columns.Add(new DataColumn("ID", typeof(int)));
if (!IsPostBack)
{
var list = (List<int>)Session["Ids"];
foreach (int id in list)
{
if (Request.QueryString["bookID" + id] != null)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = Request.QueryString["bookID" + id];
dtBooks.Rows.Add(row);
}
}
GridView1.DataSource = dtBooks;
GridView1.DataBind();
}
else
{
}
}
but I get no GridView table on the second page. I would be very grateful if anyone notices my mistake and points it out. Hope you can help me.
This is a common issue when setting session variables before a redirect. I think you can work around it by using the overloaded Response.Redirect method:
Response.Redirect("...", false); // false = don't stop execution
See here for more details:
Session variables lost after Response.Redirect
Another option is to store the IDs in a hidden field, and access them with Page.PreviousPage, like this:
HiddenField hidden = (HiddenField)Page.PreviousPage.FindControl("MyHiddenField");
string values = hidden.Value;
Lastly, depending on what the page is doing, you might want to use Server.Transfer here. There are drawbacks to this approach, but there are situations where it's applicable.
In your second page, you are checking for a query string variable before adding a row to dtBooks:
if (Request.QueryString["bookID" + id] != null)
However, you are not passing any query strings when you redirect:
Response.Redirect("SecondPage.aspx");
At a guess, I would think that you originally tried using the query string to pass the IDs, before changing to the session and you haven't updated all of your code.
I am somewhat concerned about your first page code, though. You do realize that you will redirect to the second page whenever a post back occurs? That means that no matter what buttons / controls you have on the first page, if they post back for any reason, you will redirect to the second page.
EDIT AFTER COMMENTS
If you aren't using the query string, then don't use the query string:
foreach (int id in list)
{
DataRow row;
row = dtBooks.NewRow();
row["ID"] = id;
dtBooks.Rows.Add(row);
}

Dropdown gets cleared [duplicate]

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.

Categories

Resources