Dropdownlist first value display "choose" - c#

I want that my dropdownlist display first value: "-choose car-"
I succeed at this way:
protected void ddl1_DataBound(object sender, EventArgs e)
{
Convert.ToInt32(ddl1.SelectedValue);
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
and that's ok,the "-choose-" is in the first place but the problem now is that if I have values,for example,the dropdownlist show like that:
-Choose car-
Subaro
Fiat
Honda
The first value that display when I'm enter to the site is the Subaro,and to see the -choose car- the user need to open the dropdownlist and then he will see the -choose car- at the first place.How can I do that from the start,from the page load - the -choose car- will display at the ddl from the page load.Where I wrong at the code ?
I tried the itemlist with AppendDataBoundItems = "true" but I got an error, and when I succeed,the problem is the same like I said before.

You were on the right track with using the AppendDataBoundItems property, it should be set to true if you're databinding the list.
Your markup should look like this
<asp:DropDownList runat="server" ID="ddl1" AppendDataBoundItems="true">
<asp:ListItem Text="-Choose car-" />
</asp:DropDownList>
and your code behind probably already looks something like this
ddl1.DataSource = [your datasource goes here];
ddl1.DataBind();
This will place the Choose car text as the first option in the drop-down list and append the rest of the options below it.
Now for the more interesting part of why you were seeing the behavior you were seeing (first item not being selected). If you look at the implementation of SelectedIndex using a tool like JustDecompile (not affiliated with Telerik, just happen to use their tool) you'll see code that looks like this:
public int SelectedIndex
{
get
{
int num = 0;
num++;
while (num < this.Items.Count)
{
if (this.Items[num].Selected)
{
return num;
}
}
return -1;
}
set
{
// stuff you don't care about
this.ClearSelection();
if (value >= 0)
{
this.Items[value].Selected = true;
}
// more stuff you don't care about
}
}
As you can see, the index isn't stored anywhere, it's computed every time based on which item has the Selected property set to true. When you set the SelectedIndex to 0 in the markup and databind your datasource, it will select the 0th item in that list, in your case Subaro. When you insert a new item at the beginning of the list, Subaro is still marked as the selected item, which is why when the page loads, you see that selected and not Choose car. If you want to mark Choose car as the selected item using code, you will have to do it after you data databind your dropdown. Please note, this is just an implementation detail of how DropdownList works. It could change in future version of ASP.NET so do not write code that relies on it working this way.

Make sure that you bind the data source and insert you "-choose care-" item first before selected he first item
make sure when you insert your 1st item "-Choose car-" you make it once not on each PostBack. Check if not IsPostBack to add the 1st item.
EDIT:
Example:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
ddl1.SelectedIndex = 0;
}

You should do ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-")); first, and than ddl1.SelectedIndex = 0

private void FillCar()
{
DataTable dt = GetCar();
ddl1.Items.Clear();
ddl1.DataSource = dt;
ddl1.DataTextField = "carName"; // field name in the database
ddl1.DataValueField = "CarNum"; // field name in the database
ddl1.DataBind();
ListItem li = new ListItem();
li.Text = "--Choose car--";
li.Value = "-1";
ddl1.Items.Insert(0, li);
ddl1.SelectedIndex = 0;
}
I use method like this and call it in the page load in if (!IsPostBack){}.

Related

Setting dropdownlist values from selected value

I have a dropdownlist which contains some values such as "Hot water" and "Electricity" in C# ASP.Net. What I would like to do is if the user selects one of these values and clicks on a button, then it would set the values of a second dropdownlist to certain values. e.g. if "Hot Water" was chosen and next was clicked then the values in dropdownlist2 would be "Radiator" and "Heating controls". But if "Electricity" was chosen then the values in dropdownlist2 would be "No Power" and "Sockets". My code so far:
protected void NextButton1_Click(object sender, EventArgs e)
{
option1 = DropDownList1.SelectedValue.ToString();
TextBox1.Text = option1;
DropDownList2.Visible = true;
if (DropDownList1.SelectedValue == "Hot Water")
{
DropDownList2.SelectedValue = "Heating controls";
DropDownList2.SelectedValue = "Underfloor Heating";
}
}
I hope I understood you with the following:
if(DropDownList1.SelectedValue == "Hot Water"){
DropDownList2.Items.Clear();
DropDownList2.Items.Add("Radiator");
DropDownList2.Items.Add("Heating Controls");
}
if(DropDownList1.SelectedValue == "Electricity"){
// Do the same like above but for the values in Electricity
}
Don't think you can multi-select in a dropdown list so use a asp:ListControl or asp:CheckBoxList instead.
If you want a dropdown multiselect there are plenty of JS controls that will do that for you.
eg: https://harvesthq.github.io/chosen/
Once you update your code for a list than everything should work fine.
First check whether the Hot Water or Electricity is selected in the dropdownlist1 in Nextclick button code like this.
if(dropdownlist1.SelectedValue == "Hot Water")
{
drodownlist2.Items.Add(new ListItem("Radiator","Radiator")); //First parameter take datatextfield and second parameter take datavaluefield.
drodownlist2.Items.Add(new ListItem("Heating Controls","Heating Controls"));
}
else
{
drodownlist2.Items.Add(new ListItem("No Power","No Power"));
drodownlist2.Items.Add(new ListItem ("Sockets","Sockets"));
}

asp.net dropdownlist does not remember choice

I'm currently running into a head-scratching bug in my ASP.NET Windows Form App. I have two DropDownList, implemented them in the same way, yet they behave differently.
The problem:
When selecting an item in the DropDownList "GroepSelect", the page refreshes (as intended), but resets it's SelectedIndex to the first item.
When selecting an item in the DropDownList "VakSelect", the page refreshes, but also remembers it's SelectedIndex value.
It's doing this behavior consistently, yet I am unable to discover what I do wrong.
My Code:
In my HTML code, I have two DropDownList Controls.
<div>
<asp:DropDownList runat="server" ID="GroepSelect" AutoPostBack="true" AppendDataBoundItems="true" />
<asp:DropDownList runat="server" ID="VakSelect" AutoPostBack="true" AppendDataBoundItems="true" />
</div>
I'm populating the controls in my C# code:
protected void Page_Load(object sender, EventArgs e) {
Database db = new Database();
if (!IsPostBack) {
GroepSelect.DataSource = GenereerDummyGroepen(); // returns a List<ListItem>
GroepSelect.DataTextField = "Text";
GroepSelect.DataValueField = "Value";
GroepSelect.DataBind();
GroepSelect.SelectedValue = "1";
VakSelect.DataSource = db.GetVakken(); // returns a List<Vak>
VakSelect.DataTextField = "Omschrijving";
VakSelect.DataValueField = "Id";
VakSelect.DataBind();
VakSelect.SelectedValue = "1";
}
// Use the SelectedValue to determine which data to get out of the database
Medewerkers = db.GetMedewerkers(int.Parse(GroepSelect.SelectedValue));
Opdracht = db.GetOpdrachten(int.Parse(VakSelect.SelectedValue)).First();
Resultaten = db.GetResultaten(Opdracht.Id, int.Parse(GroepSelect.SelectedValue));
GenereerTabel();
}
As requested, my code for GenereerDummyGroepen() is the following:
private List<ListItem> GenereerDummyGroepen() {
return new List<ListItem>()
{
new ListItem("Groep 1", "1"),
new ListItem("Groep 2", "1")
};
}
Why I implemented it this way?
I try to populate a custom-made pivot table based on the content of Medewerkers, Opdracht and Resultaten. The content of those lists, depends on the selected item in the DropDownList control. The expected behavior of those controls is, that on the moment those are changed, the table should re-populate. The strategy I follow here, is that a page-postback is being processed, and using the AppendDataBoundItems=true remembers the DropDownList contents so that on the newly refreshed page I can generate the table.
My Question
I'm looking for the answer for: why is there a consistent different behavior? Is it the fact that the ListItem class differs in behavior from my custom class Vak?
Here I guess issue is with you function
GenereerDummyGroepen();
Please put your code here. In your code there is value field might have same data for all listItem. Because of that it is changing default to firstIndex as all values are same.

ASP.NET How do I check ever row in the gridview?

I want to add value into a Grid view via dropdownlist with a button.
I want the ddTN.SelectedItem.value in the Grid view to be unique. No duplication
How do I check every row for the ddTN.SelectedItem.value before adding a new ddTN.SelectedItem.value into the Grid view?
This are the codes that I have and it keep comparing the value with the first value in the gridview. Not the others.
I don't want to use a checkbox and such. All the example I found required using checkbox.
protected void Insert(object sender, EventArgs e)
{
int i = 0;
var p = 1;
DataControlFieldCell cell = GridView1.Rows[i].Cells[p] as DataControlFieldCell;
if (cell.Text != ddTN.SelectedItem.Value)
{
dt.Rows.Add(ddTN.SelectedValue, ddDuration.SelectedValue);
ViewState["Customers"] = dt;
this.BindGrid();
label.Text = "";
p++;
}
else
{
label.Text = "Exercise already inserted";
}
}
It looks like you were intending on looping over the items in the grid but you have forgotten the looping mechanism. In your code, it always only checks the first item because i is initialized to 0 and never changes.
Try using a looping mechanism like a for loop or a while loop. Or, if you know the items in the grid from the beginning, perhaps use a hash table for quickly checking if the selected item already exists.
Keep trying, you are almost there!

Error on passing data back to Dropdownlist asp .net webform

I have a dropdownlist that cannot be used for editing purpose. When button Edit is clicked inside listview where data exists, data is supposed to pass back to dropdownlist and other textboxes where the form is located outside listview. Passing data back to textboxes is ok. The problem is dropdownlist data that I want to edit was added to dropdownlist as another record. Please take a loot at picture, and I have to reselect the correct one. Otherwise, that selected data (e.g. December in picture) has no datavaluefield and it stops running if I didn't choose bottom December and click Update button. Here is my code for dropdownlist for months. Any help is appreciated for this. Thank you.
public void BindMonth()
{
ddlStartMonth.DataSource = objUIHelpers.GetAllMonths();
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
Then, I put this method in page load like this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindMonth();
}
}
This is listview data item editing
protected void lvEducation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
//Delete Method will be fired when command name "Delete" inside Listview is clicked.
case ("Delete"):
int EducationId = Convert.ToInt32(e.CommandArgument);//pass Id of Experience to identify datarow to delete
// DeleteEducationById(ExperienceId);//Call bind to delete method and pass ExperienceId as argument
break;
//Edit Method will fired when command name "Edit" inside Listview is clicked.
case ("Edit"):
EducationId = Convert.ToInt32(e.CommandArgument); //pass Id of Experience to identify datarow to edit
BindEducationDataToEdit(EducationId);//Call bind to edit method and pass ExperienceId as argument
break;
}}
This is part of method that triggers to pass back data to edit.
public void BindEducationDataToEdit(int EducationId)
{
Education edu = objJFUserBAL.GetEducationByIdToEdit(EducationId);
txtAdditionalInfo.Text = edu.AdditionalInfo.ToString();
ddlEndMonth.SelectedItem.Text = edu.mo.EndMonthName;
}
When selected data is posted back for editing, I have extra data like this.
You should not be updating the SelectedItem.Text. This is changing the displayed text. Instead you should be updating which item is selected.
If you do not have access to the value of the month name, you can do the following:
ddlEndMonth.Items.FindByText(edu.mo.EndMonthName).Selected = true;
which will select the item with the month text assuming one exists.
If it is possible to have an edu.mo.EndMonthName which does not exist in the list of items, you will want to do some checks for null and treat accordingly.
You have to fill a list manually, because auto binding is not going to let you put a "select your month" item unless you have one in your data base :
public void BindMonth()
{
List<Month> listOfMonth = new List<Month>();
Month fakeMonth = new Month();
// you need to see your own
//code and try to make a fake month with these parameters you want
fakeMonth.StartMonthName = "Select Start Month";
fakeMonth.MonthId = 0;
listOfmounth.Add(fakeMonth);
foreach(Month m in objUIHelpers.GetAllMonths())
{
listOfMonth.Add(m)
}
ddlStartMonth.DataSource = listOfMonth;
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
}

Dropdown gets cleared

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