Get selected Value from dropdownlist after submit? - asp.net

I populate DropDownList in ASP.NET webforms:
<asp:DropDownList runat="server" ID="salesman"></asp:DropDownList>
users= Buslayer.GetSalesRep();
foreach (userentity user in users)
{
salesman.Items.Add(new ListItem(user.FirstName + " " + user.LastName,
user.UserID.ToString()));
}
After submission, I am still getting selected index = 0,
I tried all of this but failed:
Response.Write("" + salesman.SelectedValue);
Response.Write("" + salesman.SelectedItem.Value);
Response.Write("" + salesman.SelectedIndex);

Are you checking for the Page posting back with you databind?
Your page load should look something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
// Get your data
ddl.DataSource = yourData;
ddl.DataBind();
}

Related

Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount

i want to bind my data Gridview but it throw an error.
i allow paging when i click on new page e.g 1.2.3 then the above error throw
here is my code.
the one is page index change and the other one is my method of BindGrid.
the error come when i click one new page 2 or 3 etc
updated code
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["data"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days, CaseTypeID, CollectorID, user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["data"] = data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
Problem what is happening is when you fetch the data again in BindGrid() method you must be getting less number of pages.so you can do two things.
1)If you are filtering your data then reset the page index to 1.
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
BindGrid();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
DataGrid1.DataSource = data;
DataGrid1.CurrentPageIndex = 0;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
2)If you are not filtering your data then store the datagrid value in a session object and use this for pageing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["value"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["value"]=data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
DataGrid1.DataSource = data;
DataGrid1.DataBind();
DataGrid1.CurrentPageIndex = 0;
Reset the CurrentPageIndex to 0 after the page has been bound.

Cannot get the selected value of combobox in asp.net

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.

DropDownList bug - OnSelectedIndexChanged fires only when DDL is filled in HTML

Step 1. The DropDownList is filled with items on Page_Load.
Step 2. I select an item and it initiates postback. During this postback Page refreshes first, then OnSelectedIndexChanged fires and "ddl1_Select" function runs.
If I statically fill the DropDownList with data in Aspx (HTML) file, it works properly.
But, if I fill it in code-behind, the OnSelectedIndexChanged event never fires and DDL1_Select procedure doesn't start. Page just posts back and skips my procedure. Why doesn't this event fire and how to make it work?
ASPX:
<%# Page Language="C#" MasterPageFile="~/Master.master" AutoEventWireup="true"
CodeFile="mypage.aspx.cs" Inherits="mypage" Title="mypage" EnableViewState="False" %>
...
<asp:DropDownList ID="ddl1" runat="server" OnSelectedIndexChanged="ddl1_Select" AutoPostBack="True"/>
ASPX.CS:
protected void Page_Load(object sender, EventArgs e)
{
ddl1.Items.Add("1");
ddl1.Items[0].Value = "1";
ddl1.Items.Add("2");
ddl1.Items[1].Value = "2";
ddl1.Items.Add("3");
ddl1.Items[2].Value = "3";
if (Session["NewSelection"] != null) // see note 1
{
string itemValue = Session["NewSelection"].ToString();
ddl1.SelectedIndex = ddl1.Items.IndexOf(ddl1.Items.FindByValue(itemValue));
Session["NewSelection"] = null; // see note 1
}
}
protected void DDL1_Select(object o, EventArgs e)
{
Session["NewSelection"] = ddl1.SelectedValue;
Page.Response.Redirect("mypage.aspx?test=" + Session["NewSelection"].ToString());
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddl1.Items.Add("1");
ddl1.Items[0].Value = "1";
ddl1.Items.Add("2");
ddl1.Items[1].Value = "2";
ddl1.Items.Add("3");
ddl1.Items[2].Value = "3";
if (Session["NewSelection"] != null) // see note 1
{
string itemValue = Session["NewSelection"].ToString();
ddl1.SelectedIndex = ddl1.Items.IndexOf(ddl1.Items.FindByValue(itemValue));
Session["NewSelection"] = null; // see note 1
}
}
}

CommandButton event not firing

I am populating an html table from a datatable with an edit button in each table row for each datatable row.
I am adding the edit button in code as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (UserName != null && UserName != "")
{
hUserName.Value = UserName;
}
else
if (hUserName.Value != "")
UserName = hUserName.Value;
ShowTrainingEntry();
ShowUserTraining(); <-------------- this method populates table
hTID.Value = TrainingID.ToString();
}
}
public void ShowUserTraining()
{
....
dTotalTrainingHours += ShowTrainingInPeriod(dv);
....
}
protected decimal ShowTrainingInPeriod(DataView dv)
{
....
foreach (DataRowView rowView in dv)
{
....
Button bEdit = new Button();
int iTID = Convert.ToInt32(dr["ID"].ToString());
bEdit.Text = "Edit";
bEdit.ID = "btnEdit_" + iTID.ToString();
bEdit.CommandName = "Edit";
bEdit.CommandArgument = iTID.ToString();
bEdit.Command += new CommandEventHandler(btnEdit_Click);
....
}
....
}
public void btnEdit_Click(object sender, CommandEventArgs e)
{
clsLog.WriteLog("btnEdit_Click fired.");
clsLog.WriteLog("\t" + e.CommandName);
clsLog.WriteLog("\t" + e.CommandArgument.ToString());
UserName = hUserName.Value;
TrainingID = Convert.ToInt32(e.CommandArgument);
ShowTrainingEntry();
ShowUserTraining();
}
as requested - HTML table:
<asp:Table ID="tblMain" runat="server" Width="900" CellPadding="3" CellSpacing="0" CssClass="noborder">
</asp:Table>
btnEdit_Click is NOT being fired (no log entries).
I have researched this for several hours and the only thing consistent I have found is that the event must be wired to the button during Page_Load which I believe is happening correctly.
Any help would be greatly appreciated.
Thanks,
John
try to do event register
btnEdit_Click.Click += new EventHandler(this.btnEdit_Click);

Call a button_click on page_load asp.net

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.

Resources