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.
Related
I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"
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.
I am trying to use two DropDownLists to filter data. I set both of the OnSelectedIndexChanged Equal to the method below. The problem is it is only grabbing the SelectedIndex of the DDL that is changed. Example: if i choose a option in DDL1 it grabs that value and doesnt grab the value of DDL2. They both have the same OnSelectedIndexChanged i figured it would grab the current value of both. Is there a way to make it look at both DDL Controls?
protected void BrandsList_SelectedIndexChanged(object sender, EventArgs e)
{
int DDLcatId = CategoriesList.SelectedIndex;
int DDLBraId = BrandsList.SelectedIndex;
IQueryable<Product> DDLprodResult = GetProductsDDL(DDLcatId, DDLBraId);
if(DDLprodResult == null)
{
}
else
{
CatLab.Text = DDLprodResult.ToList().Count().ToString();
productList.DataSource = DDLprodResult.ToList();
productList.DataBind();
}
}
Your code should work. Of course only one can be changed if you have set AutoPostBack="true"(default is false) on both. But you should get the correct SelectedIndex anyway in the handler.
So i will guess: you are databinding the DropDownLists on every postback. Do this only if(!IsPostBack), otherwise you always overwrite changes with the original values.
So for example in Page_Load:
protected void Page_Load(Object sender, EvengtArgs e)
{
if(!IsPostBack)
{
// DataBind your DropDownLists
}
}
I think this issue has a simple solution but I have been banging my head on it for a few days now. I have a web application in which Dynamically gets a list of students from a stored procedure. I want to look at detailed information for each student and subsequent class information. On the Student's Details page, there is a dropdown list that contains all the classes that the student is in and when one is selected, the Community Partner field should be updated.
I am using SelectedIndexChanged method but in order to make it work, I need to set AutoPostBack to True and that causes the page to reload and thus the dropdown list and selected value to reload as well. I have tried several different configurations of this code with no results.
Here is my ascx file
<asp:DropDownList ID="StudentCourses" runat="server"></asp:DropDownList>
And here is my ascx.cs file
protected void Page_PreRender(object sender, EventArgs e)
{
if (Session["StudentID"] != null)
{
int studentId = Convert.ToInt32(Session["StudentID"]);
Student student = studentRepository.GetStudent(studentId);
StudentCourses_SelectedIndexChanged(sender, e);
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
...
And here is my SelectedIndexChanged method
protected void StudentCourses_SelectedIndexChanged(object sender, EventArgs e)
{
IList<KeyValuePair<Course, CommunityPartner>> courseList = studentRepository.GetStudentCourses(Convert.ToInt32(Session["StudentID"]));
StudentCourses.DataSource = courseList;
StudentCourses.DataBind();
int ctr = 0;
foreach (KeyValuePair<Course, CommunityPartner> kvp in courseList)
{
if (ctr < StudentCourses.Items.Count)
{
StudentCourses.Items[ctr].Text = kvp.Key.CourseCode;
StudentCourses.Items[ctr].Value = kvp.Value.PartnerName;
ctr++;
}
else ctr = 0;
}
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
}
I have tried several combinations and I am at a loss as to how to properly change the content on the page without the dropdownlist refreshing every time I do. Thanks for your help, it is much appreciated.
To set a textbox off of a drop down change look here:
set dropdownlist value to textbox in jQuery
If you have more that you want to do, the selected value from the drop down should be kept in the view state on post back. You might try saving that value
var Selected = StudentCourses.SelectedValue;
populate the drop down
and then set the selected value with the saved value
StudentCourses.SelectedValue = Selected;
I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app
I have a ASP DDL like
<asp:DropDownList ID="DDLProgram" runat="server"
OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
</asp:DropDownList>
My OnDDLProgramChanged method is defined as
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
//My Problem goes here
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.
Can anyone help me in this case?
You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event
It should be like..
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
You have to bind data to the DropDownList on page load method
if (!IsPostBack)
{
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
}
Otherwise it will bind data everytime and hence clear the selection
Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.