I created a dropdown combobox in asp.net. Here it is:
<asp:ComboBox ID="dropdown_course3" runat="server" AutoPostBack="False"
DropDownStyle="DropDownList"
AutoCompleteMode="Suggest" CaseSensitive="False"
ItemInsertLocation="Append">
</asp:ComboBox>
Then i have a button in my page, and when i click it, i want to get the value of selected item in combobox. The button causes postback. Here is my code:
protected void button_conflict_check_button_Click(object sender, EventArgs e)
{
string dr3 = dropdown_course3.Text;
}
But this returns an empty string even though it should not be empty. Also, i tried selectedItem and it returns null. Can anyone help me with this?
And also, here is how i fill the combobox:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable subjects = new DataTable();
CommonFunctions.con.ConnectionString = CommonFunctions.getConnectionString();
CommonFunctions.con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [crn], [subj], [numb], [section] FROM Courses", CommonFunctions.con);
adapter.Fill(subjects);
foreach (DataRow dr in subjects.Rows)
{
string displayVal = dr["subj"].ToString() + " " + dr["numb"].ToString() + " " + dr["section"].ToString();
dropdown_course1.Items.Add(new ListItem(displayVal));
dropdown_course2.Items.Add(new ListItem(displayVal));
dropdown_course3.Items.Add(new ListItem(displayVal));
}
}
catch (Exception ex)
{
// Handle the error
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
CommonFunctions.con.Close();
}
}
Thanks
I have found the problem, since i fill the combobox at page load and inside if(!Page.IsPostBack) block, the button causes postback and combobox seems to be empty.
Related
I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback
After much much research I cannot find the same problem anywhere, under my circumstances. I've enabled viewstate at the page, control, and individual dropdown levels. Page_Load only loads the dropdown if PostBack true according to code.
The problem is that on postback (triggered by the DropDownList or any control), "Empty Parameter" shows in my debugging label, which tells me it's not grabbing the SelectedValue from the dropdown in its selectedIndexChanged method. Also, my dropdowns reset to their initial value before the PageLoad "PopulateFilterDropdowns" method.
Any ideas? I've been searching here, google, anywhere and everywhere I can go. Everybody's problem is usually a lack of "IsPostback" or EnableViewState="true", but no dice on my end. I will mention this is a ascx UserControl, inside of a page with a MasterPage. But I believe the code of each of those is irrelevant to this problem, and quite large to post here.
Help!?
Dropdown:
<asp:DropDownList ID="ddlTopics" runat="server" EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="ddlTopics_SelectedIndexChanged">
<asp:ListItem Text="Topic" Value=""></asp:ListItem>
</asp:DropDownList>
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateFilterDropdowns();
}
}
Following methods:
public void PopulateFilterDropdowns()
{
PopulateTopicDropdown();
PopulateAssetTypeDropdown();
PopulateLevelDropdown();
}
public void PopulateTopicDropdown()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXX"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("StoredProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
//ListItem itm = new ListItem();
//itm.Value = rdr[0].ToString();
//itm.Text = rdr[0].ToString();
ddlTopics.Items.Add(new ListItem(rdr[0].ToString(), rdr[0].ToString()));
}
}
}
}
}
Problem zone:
protected void ddlTopics_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlTopics1 = (DropDownList)sender;
string topic = ddlTopics1.SelectedValue;
if (String.IsNullOrEmpty(topic))
lblDebug.Text = "Empty Parameter";
else
lblDebug.Text = topic;
//PopulateRecordsByTopic(topic);
}
public void PopulateRecordsByTopic(string topic)
{
//Query and Binding of repeater on page
}
I have populated a dropdownlist from a database. Now on select of a particular item I want the data to come from the database and get displayed in a label, but, when I am selecting a particular item, the page gets loaded again and in the dropdownlist --SELECT-- comes again and not the value which I previously selected.
My code is-
aspx page-
https://stackoverflow.com/editing-help
codebehind-
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UI"]==null)
{
Response.Redirect("AdminLogin.aspx");
}
else
{
if (!IsPostBack)
{
AddVehicle vb = new AddVehicle();
DataSet tt = vb.populatedropdown();
DropDownList1.DataSource = tt;
DropDownList1.DataTextField = "DealerID";
DropDownList1.DataValueField = "DealerID";
DropDownList1.DataBind();
}
}
}
I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}
I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.