Display DB values in a Dropdown list [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Display DB values in a dropdownlist
I am fetching DB values and displaying them in the Dropdown list. I have country and state drop down lists:
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()));
DropDownList2.Items.Add(new ListItem(Session["state"].ToString()));
I am unable to show the DB values in the DDL. I am getting --select a state--
in the state Dropdown list how to show the DB values in the Dropdown list?
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True">
<asp:ListItem Value="Select a state" >Select a state</asp:ListItem>
<asp:ListItem Value="value 1" >Maharastra</asp:ListItem>
<asp:ListItem Value="value 2" >Goa</asp:ListItem>
<asp:ListItem Value="value 3" >Kashmir</asp:ListItem>
</asp:DropDownList>
i am cacthing the DB values here and sending them to the next page
if (dt.Rows.Count > 0)
{
DataTable dt1 = new DataTable();
dt1 = bll.getnewid(TextBox1.Text);
if (dt1.Rows.Count > 0)
{
Session["country"] = dt1.Rows[0]["Country"].ToString();
Session["state"] = dt1.Rows[0]["State"].ToString();

Well, you must somehow bind your ddlist to the db results. Looks like this:
ddlist1.DataSource = MyDBAccessClass.GetSomeValues();
ddlist1.DataBind();
Based on more comments... I'll have to play a little roulette and guess what's your intentions. Your code has multiple problems and you've obviously some issues explaining yourself.
If I understood you correctly, you have 2 dropdownlists. You want to populate one with countries and based on the selection, populate the second dropdownlist.
The basic principle looks like this:
DataAccessClass.cs
public class DataAccessClass
{
public static IEnumerable<string> GetCountries()
{
// access the database and retrieve all the values
// returns IEnumerable (a list of items)
}
public static IEnumerable<string> GetStates(string selectedCountry)
{
// access the database and retrieve all the corresponding states
// linq2sql: var states = from o in db.States
// where o.country = selectedCountry
// select o;
// returns IEnumerable (a list of items)
}
}
YourPage.aspx
<asp:DropDownList id="ddlistCountries" runat="server" AutoPostBack="True" /><br />
<asp:DropDownList id="ddlistStates" runat="server" />
YourPage.aspx.cs
public partial class YourPage
{
protected void Page_Init(object sender, EventArgs e)
{
ddlistCountries.SelectedIndexChanged += new EventHandler(ddlist_SelectedIndexChanged);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!isPostBack)
{
PopulateCountries();
ddlistStates.Enabled = false; // no country selected yet!
}
}
protected void PopulateCountries()
{
ddlistCountries = DataAccessClass.GetCountries();
ddlistCountries.DataBind();
ddlist.Items.Insert(0, "Select a country");
}
void ddlist_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlistCountries.SelectedIndex != 0)
{
ddlistStates.DataSource = DataAccessClass.GetStates(ddlistCountries.SelectedValue);
ddlistStates.DataBind();
ddlistStates.Enabled = true;
}
else
{
ddlistStates.Items.Clear();
ddlistStates.Enabled = false;
}
}
}
If you can't understand this, either go back to basics or forget about programming altogether.

DropDownList2.DataSource = {your data source};
DropDownList2.DataTextField = "text column name";
DropDownList2.DataValueField = "data column name of id";
DropDownList2.DataBind();
You need to set your data source to the DDL, then set which values to display, then bind it.

I would suggest to use the dropdownlist like this :
ddl.DataSource = YourDBSource.Get();
ddl.DataBind();
you can then decide what to be displayed here with :
ddl.DataTextField = ...;
or
ddl.DataValueField = ...;
First of all, there is no reason to build your listItem in the .aspx page because you will populate your ddl programmatically.
Secondly I don't know what you mean by 'i am cacthing the DB values here and sending them to the next page'. Just fill the dataSource with the appropriate query on you DB.
If you want to perform more easy filtering / wahtever you want, try to use Linq2SQL.
Additionally, you need to perform this databinding in the *Page_Load()* like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlErreur.DataSource = ...;
ddlErreur.DataTextField = ...;
ddlErreur.DataBind();
}
}

Related

How to put a label into a checkboxlist from another page for asp.net

I tried doing this on the check box list page:
protected void Page_Load(object sender, EventArgs e)
{
(string)Session["name"] = cbl1.Items.Add;
}
but I don't know how to make it work.
You don't really "put a label into" a check box list from another page.
You might say have a check box list on one page, and you want to pass the selection(s) made in the first page, and pass to the 2nd page.
So, say we have a simple check box list of options on page 1
And a button to jump to the next page.
This markup:
<h3>Hotel Options</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="ID"
DataTextField="HotelOption" >
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Continue to next page" CssClass="btn" OnClick="Button1_Click" />
And code to load this up:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
DataTable rstOptions =
MyRst("SELECT ID, HotelOption FROM tblOptions ORDER BY ID");
CheckBoxList1.DataSource = rstOptions;
CheckBoxList1.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Hotels))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And we now have this:
Ok, so now our code for the button.
We will get + save the above selections, and pass to the next page:
protected void Button1_Click(object sender, EventArgs e)
{
Session["MyItems"] = CheckBoxList1.Items;
Response.Redirect("WebForm2.aspx");
}
Ok, now our markup for the 2nd page.
We have this:
<h3>Hotel Options - on next page</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="Value"
DataTextField="Text" >
</asp:CheckBoxList>
<br />
Now, we saved the "items list" for the Check box list. The item list has a text and value property (we LOSE the colum name information that the data sourced used was).
So, note how the DataValueField="value" and DataTextField="Text" now.
So, this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach (ListItem OneItem in MyItems)
{
CheckBoxList1.Items.Add(OneItem);
}
}
And now on 2nd page we have this:
Now it is NOT clear why I can't just bind this passed list directly to the check box list, but I found a foreach loop is required.
Now, it is perhaps not clear, but maybe you ONLY wanted the label text ones selected.
You can do this with this code:
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach(ListItem OneItem in MyItems)
{
if (OneItem.Selected)
{
Debug.Print("Label text = " + OneItem.Text);
Debug.Print("Check box value = " + OneItem.Value);
}
}
Output:
Label text = Smoking
Check box value = 1
Label text = Balcony
Check box value = 2
So, keep in mind that a check box list can often have 2 columns of data.
The display "label" or text, or the hidden value.
In my example, the "ID" is the PK value from the database, and I need that.
If you only have one "text" value, and don't care about a hidden database PK value, then often I just set both DataTextField and DataValueField to the SAME column in the database.
And if you using looping, and adding a listitem in code? Then the settings are not the field columns anymore, but Text and Value. You thus still have the ability to have 2 values - the display text, and some key or number value for a checkbox list.
Now perhaps you have two web pages open, and you want to change/set controls in the other web page?
No, you can't do that. Other web pages might say be open to someone's banking web site. You can't mess around with other web pages the user has open, since that would be a MASSIVE security hole, and no one would risk using the world wide web then, right?
Edit: placing the results on a label on the 2nd page
Ok, so the debug.print? That is just a handy debugging way of displaying some code values - only for developers. It really much like using console.log to display value(s) into the console. It certainly not for putting some text into a label (I realy thought that would be crystail clear to you - at a loss as to why you think debug.print has anything of value or is relavent to YOU writing code to put a few text values into a label).
So, ok, on the 2nd page we will have a label and not some check box list.
So, our markup on the 2nd page will now look like this:
<asp:Label ID="Label1" runat="server" Text=""
Font-Bold="true"
Font-Size="Large"
></asp:Label>
And in our page load event, we will have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadLabel();
}
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += ",";
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
So, now on first page, we say select this:
And now on 2nd page, we see this:
Of course, we could change our code to display each choice on a new line,
Say this code:
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += #"<br/>"; // <-- new line in label
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
And now we would see this:
So, you can shove results into that label - separated by ",", or whatever.
Or, you can display the choices on a new line as per last example.

ASP.NET Dropdown list has a SelectedValue which is invalid because it does not exist in the list of items

My question is very simple, i found lots of example but they are not concise and to the point.
below is the markup in my aspx file
<asp:DropDownList ID="ddlCountry" DataTextField="CountryName" DataValueField="CountryCode" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
and following is the my code behind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadCountry();
this.ddlCountry.SelectedValue = "USA";
}
}
private void LoadCountry()
{
DataTable dtResult = null;
dtResult = new DataTable("Countiers");
dtResult.Columns.Add("CountryCode");
dtResult.Columns.Add("CountryName");
DataRow dtRow1 = dtResult.NewRow();
dtRow1["CountryCode"] = "PAKISTAN";
dtRow1["CountryName"] = "PAKISTAN";
dtResult.Rows.Add(dtRow1);
DataRow dtRow2 = dtResult.NewRow();
dtRow2["CountryCode"] = "INDIA";
dtRow2["CountryName"] = "INDIA";
dtResult.Rows.Add(dtRow2);
DataView dv = new DataView(dtResult);
dv.Sort = "CountryName";
this.ddlCountry.DataSource = dv;
this.ddlCountry.DataBind();
this.ddlCountry.Items.Insert(0, new ListItem("--Please Select--", "-1"));
}
protected void Button1_Click(object sender, EventArgs e)
{
this.ddlCountry.SelectedValue = "USA";
}
}
i am simply loading this drop-down with countries, during initial page load event after calling LoadCountry method i am setting selectedValue to "USA" which gives no exception or error. But after postback by clicking Button1 i am again setting selectedValue to "USA" but this time exception occurred (has a SelectedValue which is invalid because it does not exist in the list of items). I understand the value "USA" is not in the list thats why it throws exception but why it didnt throws that exception initially?
It's a documented behaviour, but I actually don't know the reason for this:
When the selected value is not in the list of available values and a postback is performed, an ArgumentOutOfRangeException exception is thrown.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue%28v=vs.110%29.aspx

How to include selected value in populated drop-down list

I am using linq to fetch from database to populate in drop down list in asp.net using below code:
XXXDataContext summary = new XXXDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var binmy = ( from bin in summary SUBPRODUCTs
order by bin.SUBID
select new { bin.SUBID, bin.SUBValue }
);
dropdownsummary.DataValueField = "SUBID";
dropdownsummary.DataTextField = "SUBValue";
dropdownsummary.DataSource = binmy;
DataBind();
}
}
Here I want to include 'All' as default value how to do that?
Add this item in the html dropdown declaration and set the 'AppendDataBoundItems' property to true. See below...
<asp:DropDownList ID="dropdownsummary" runat="server" AppendDataBoundItems="true">
<asp:ListItem Selected="True" Value="-1" Text="All"></asp:ListItem>
</asp:DropDownList>
Use:
dropdownsummary.DataBind();
Instead of :
DataBind();
Try This
dropdownsummary.DataValueField = "SUBID";
dropdownsummary.DataTextField = "SUBValue";
dropdownsummary.DataSource = binmy;
dropdownsummary.Items.Insert("0", new ListItem ( "All" , "0" ));

Object reference not set to an instance of an object when tring to set the selection of a combo box

I have a text box and a RadComboBox like this :
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true"></asp:TextBox>
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="Contains" ItemsPerRequest="100"
MarkFirstMatch="true" Width="380px" EnableAutomaticLoadOnDemand="True" EmptyMessage="-emp name-" ShowMoreResultsBox="True" AutoPostBack="True">
</telerik:RadComboBox>
According to the Telerik Documentation
Set a data source to the RadComboBox. Use either DataSourceID or the
DataSource property to do this and set the DataTextField and
DataValueField properties to the respective fields in the data source.
(Note that when using DataSource you must set the property on each
postback, most conveniently in Page_Init.) Set
EnableAutomaticLoadOnDemand to true.
protected void BindEmployees()
{
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
BindEmployees();
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()).Selected = true;//Get exception here Object reference not set to an instance of an object.
}
I find rad_ddl_inner_emp_name.Items.Count = 0 !! before set the selection ! How to fix this problem ?
As I'm sure you aware of by now, the radcombox typeahead functionality searches text via client side interaction and not by value, which is why you can't find the values.
What I would suggest is having a secondary object to search by emp_num (assuming that's the value that will always be entered into the textbox).
For example, create a global variable:
private Dictionary<string, string> Emp_Dict = new Dictionary<string, string>();
Then populate this dictionary when you do your binding. The following code assumes an ienumerable type being returned. If not you may have to populate the dictionary differently. Also, for this to work, you have to include (System.Linq).
var dataSource = Utilities.GetAllEmployees();
Emp_Dict = dataSource.ToDictionary(ex => ex.emp_num, ex => ex.name);
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = dataSource;
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
So now we need to use the dictionary on the text changed event.
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
if (Emp_Dict.ContainsKey(txt_inner_emp_num.Text.TrimEnd()))
{
rad_ddl_inner_emp_name.SelectedValue = txt_inner_emp_num.Text.TrimEnd();
rad_ddl_inner_emp_name.Text = Emp_Dict[txt_inner_emp_num.Text.TrimEnd()];
}
}
Now when the text changes in the text box, the radcombobox will update when a valid emp_num is entered into the textbox.
The Problem is that the Items only get loaded when you request them!
Set
EnableAutomaticLoadOnDemand="False"
and it will work!
UPDATE:
if you want to use LoadOnDemand set these two Properties and delete the EnableAutomicLoadOnDemand!
EnableLoadOnDemand="True"
EnableItemCaching="True"
UPDATE 2:
Enable ItemCaching isn´t necessary, but it doesn´t hurt!
You do not need to bind data to RadComboBox on every postback unless you disable the view state.
Filter, MarkFirstMatch and EnableAutomaticLoadOnDemand are not useful in your case as you are loading all employees by yourself.
LoadOnDemand basically is when user starts typing inside ComboBox, ComboBox fires ItemsRequested event and retrieves data via ajax.
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true" />
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server"
CausesValidation="False" Culture="ar-EG">
</telerik:RadComboBox>
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
string value = txt_inner_emp_num.Text;
if(!string.IsNullOrWhiteSpace(value))
{
value = value.Trim();
if (rad_ddl_inner_emp_name.Items
.FindItemByValue(txt_inner_emp_num.Text.Trim()) != null)
rad_ddl_inner_emp_name.SelectedValue = value;
}
}
Since you don't have any item in rad_ddl_inner_emp_name.Items you can set txt_inner_emp_num.Text as selected in ddl.
First check if rad_ddl_inner_emp_name.Items count > 0 then set desired text selected. Or you can check if rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()) is not null.

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