DropDownList Clear Selection in C# ASP.Net - c#

I have listed employee names in one Dropdownlist. And by selecting any employee i am displaying employee details in gridview from database.
By default, dropdownlist have first item as selected item.So when i select another items it returns the first index only.
My Code:
protected void FilterBtn_Click(object sender, EventArgs e)
{
if (EmployeeList.SelectedIndex > -1)
{
sInitQuery = sInitQuery + " WHERE (EmployeeName ='" + EmployeeList.SelectedItem.ToString() + "')";
}
if (GlobalCS.OpenConnection() == true)
{
GridView1.DataSource = null;
GridView1.DataBind();
MySqlCommand cmd = new MySqlCommand(sInitQuery, GlobalCS.objMyCon);
MySqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
GlobalCS.CloseConnection();
EmployeeList.ClearSelection();
}

Put your page load code in if condition so it is just executed first time when page is loaded, other wise whenever post back happens page load gets called and your code will get executed which is the reason it gets set to first item everytime:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DisplayDatainGrid(); //All data in GridView
AddDataDropList(); //Load data in Dropdownlist
}
}
Currently every time your pageload code is exxecuting which should not happen.

Add EmployeeList.SelectedIndex to the ViewState.
protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Add("employeeListIndex", EmployeeList.SelectedIndex);
}
Then, in Page_Load, read the ViewState and assign the value to EmployeeList.SelectedIndex.
void Page_Load(object sender, EventArgs e)
{
if(ViewState["employeeListIndex"] != null)
{
EmployeeList.SelectedIndex = ViewState["employeeListIndex"];
{
}

Related

Dynamic drop down list's selected Index Changed event always return the first value

So,
I have a drop down list whish fill by a result of SQL query in my event page_Load. What i want to do it's get the current value when the event selectedIndexChanges on my drop down list is fired and put it in a textbox.
Look my code below.
My drop down list definition: <asp:DropDownList ID="ddProfil" runat="server" Width="550" AutoPostBack="True" OnSelectedIndexChanged="ddProfil_SelectedIndexChanged" >
My page load event: protected void Page_Load(object sender, EventArgs e)
{
loadDDProfil(Request.QueryString["sitename"]);
}
Function which load the drop down list:
protected void loadDDProfil(string siteName)
{
SqlCommand requete = new SqlCommand();
requete.Connection = connWeb.ConnectionToDb;
requete.CommandType = System.Data.CommandType.Text;
string strReq = "ps_get_all_IndexProfil " + "MRF";
requete.CommandText = strReq;
DataTable dtPrf = connWeb.ExecuteQueryDB(requete);
SqlDataAdapter adapter = new SqlDataAdapter(requete);
adapter.Fill(dtPrf);
var dtSource = from p in dtPrf.AsEnumerable()
select new {
ind = p.Field("IndexProfil"),
DisplayedField = String.Format("{0} [ {1} ]", p.Field("NomProfil"), p.Field("Description"))
};
ddProfil.DataSource = dtSource;
ddProfil.DataValueField = "ind";
ddProfil.DataTextField = "DisplayedField";
ddProfil.DataBind();
ddProfil.SelectedIndexChanged += ddProfil_SelectedIndexChanged;
And the event Selected Index Changed:
public void ddProfil_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddProfil.SelectedValue;
}
Thank you, for your help.
I believe your answer is here https://taditdash.wordpress.com/2014/05/21/why-dropdownlist-selectedvalue-not-working-inside-selectedindexchanged-event/
On your page load event try adding this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadDDProfil(Request.QueryString["sitename"]);
}
}

Data not displaying out despite auto-selecting gridview row

I'm trying to let the gridview auto-select the first row of data upon page load. However, in the gridview, it shows that the first row is being highlighted
but no data is being displayed in my textbox. The data only appears when i click the select button in my gridview again.
This is how i added the auto-select gridview row in my page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
}
}
This is how i get my data from my gridview to my textbox
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
Session["nric"] = gvnric.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cm = new SqlCommand("Select fullname, contact, address, email From MemberAccount Where nric = '" + Session["nric"] + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["contact"].ToString();
txtContact.Text = dr["address"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
Image1.Attributes["src"] = "MemberNricCard.aspx?";
Image1.Attributes["height"] = "200";
Image1.Attributes["width"] = "200";
}
But what could possibly caused the data not to be displayed when the first row already being selected upon page load.
I would Re Factor the code as below :
PageLoad
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
LoadFormFields();
}
gvnric_SelectedIndexChanged
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFormFields();
}
and create LoadFormFields with what you have in gvnric_SelectedIndexChanged
You can just call your gridview code in the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
gvnric_SelectedIndexChanged(this, EventArgs.Empty);
}
}

Gridview won't rebind data after changing Gridview page

I am trying to populate my gridview with amazon search results. At the moment when the page loads, datasource is filled with data. What I am trying to do is show the data after pressing the Search button, but it displays "No Records Found". I have tried many different ways, the only way it worked, was without postback, but then the issue was that every time I changed the page on the gridview, GetProducts("Playstation") command was initiated over again.
The solution I have been searcing for: Load the page -> click button -> fill the gridview with data -> When choosing new page in gridview, data is displayed but Getproducts("Playstation") is not initiated again.
Is there a way to do this ?
protected void Page_Load(object sender, EventArgs e) {
Button1.Click += new EventHandler(this.GreetingBtn_Click);
if (!Page.IsPostBack) {
AmazonSearch us = new Amazon.PAAPI.AmazonSearch();
GridView1.DataSource = us.GetProducts("Playstation");
}
}
void Search(Object sender, EventArgs e) {
Button clickedButton = (Button) sender;
GridView1.DataBind();
}
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
EDIT
I figured it out thanks to FastGeeks anwser. I added variable ds to the code. and made the following changes:
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e) {
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void Search(Object sender, EventArgs e) {
Button clickedButton = (Button) sender;
AmazonSearch us = new Amazon.PAAPI.AmazonSearch();
ds.Tables.Add(us.GetProducts("Playstation"));
GridView1.DataSource = ds;
Session["ds"] = ds;
GridView1.DataBind();
}
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
GridView1.PageIndex = e.NewPageIndex;
ds = (DataSet)Session["ds"];
GridView1.DataSource = ds;
GridView1.DataBind();;
}
You need to assign DataSource again in PageIndexChanging before binding it.
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = us.GetProducts("Playstation");
GridView1.DataBind();
}
Similarly assign DataSource in search method too.
void Search(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
GridView1.DataSource = us.GetProducts("Playstation");
GridView1.DataBind();
}
My take on this would be to store the results from the Amazon search into a DataTable, and then store the DataTable in a session variable; this is entirely possible because a DataTable is Serializable and will store in the session.
Then in your grid_PageIndexChanging event, and Search method you can retrieve the DataTable from session and re-assign your data without repeating the Amazon search.

Selecting an item in the RadioButtonList, how to get a list of items to a ListBox from database in asp.net c#

I have a RadioButtonList and a ListBox. I have bound RadioButtonList to database.
Therefore upon selecting an item in the RadioButtonList, I want to retrieve some data into the ListBox. The code I have tried is :
protected void Page_Load(object sender, EventArgs e)
{
RadioFill();
}
public void RadioFill()
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT DISTINCT Param_Name FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
RadioButtonList1.Items.Clear();
RadioButtonList1.DataSource = dset.Tables[0];
RadioButtonList1.DataTextField = dset.Tables[0].Columns["Param_Name"].ColumnName;
RadioButtonList1.DataBind();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT Value_Option FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
ListBox1.Items.Clear();
ListBox1.DataSource = dset.Tables[0];
ListBox1.DataTextField = dset.Tables[0].Columns["Value_Option"].ColumnName;
ListBox1.DataBind();
}
The issue I am facing here is upon selecting an item, the whole panel in which I have placed both my RadioButtonList and ListBox goes invisible.
Kindly help...!! Thankyou...!!
First, change Page_Load method as:
protected void Page_Load(object sender, EventArgs e)¨
{
if (!Page.IsPostBack)
{
RadioFill();
}
}
If it not help than post code from your *.aspx file.
Remark: The method RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e),
there is not selecting based on radio button list selected value.

Persisting DataTable or GridView DataSource

I have a Click Event that fills a DataTable and the DataTable is the source of my GridView.
Then I have another click event that tries to get the GridView DataSource e converts it back to a DataTable Like:
DataTable dt = (DataTable)GridView1.DataSource;
But the Datasource returns null. Event if I put the code and the Page_Init event waiting for the right postBack
so I would like to know how can i persist the datasource of the gridview, or the DataTable
edited as required:
here is the whole code:
ps: the Page_Init was another try to get the datasource
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string ctrlname = BLL.Common.GetPostBackControlId(this.Page);
if(ctrlname == "ButtonDownload")
{
DataTable dt = (DataTable)GridView1.DataSource;
}
}
}
protected void Filter_Click(object sender, EventArgs e)
{
string[] status = new string[2];
status[0] = "Paga";
status[1] = "Disponivél";
dataTable = BLL.PagSeguro.GetTransactions(TextBoxInicio.Text, TextBoxFim.Text, status);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GetDataSource(object sender, EventArgs e)
{
DataTable dt = (DataTable)GridView1.DataSource;
}
This might work for you.
public partial class Demo : System.Web.UI.Page
{
private DataTable _myData = null;
protected DataTable MyData
{
get
{
if (null == _myData)
{
// You would load your data here.
_myData = new DataTable();
}
return _myData;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Lets say you set your data source here
myGrid.DataSource = this.MyData;
}
protected void Rendering(object sender, EventArgs e)
{
// This is some other event that also needs to get at the data.
DataTable mydata = this.MyData;
}
protected void Unload(object sender, EventArgs e)
{
if (null != _myData)
{
_myData.Dispose();
_myData = null;
}
}
I'm pretty sure you can only access the datasource that way through the DataBound event or ItemDataBound event. You might be able to access the DataRowView for each item in the Items collection, but I'm not sure:
DataRow row = ((DataRowView)GridView1.Rows[0].DataItem).Row;
As for persisting the datasource, you need to consider whether that's a good idea. Your options for storing the datasource are Session or Cache, but if the result set is fairly small it might be more efficient to make another round trip when you need the datasource. Whatever you decide to do, don't store it in ViewState.

Categories