Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working - asp.net

I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataBind();
}
I don't know how to bind the gridview in paging event, since I do not have any separate binding function.

there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BusinessKPIGrid.PageIndex = e.NewPageIndex;
bindyourgrid();
}

try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
ViewState["ds"]=ds;
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
BusinessKPIGrid.DataBind();
}

From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvworker.PageIndex = e.NewPageIndex;
//result got from ddl list i.e bind your data set
}

Related

ViewState for private string with button

I have gridview with a Rowcommand event that let's me get the column ActivityID cell value and puts it in a private string called ActivityIDString.
private string ActivityIDString; // To be used in btUpdate
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ActivityIDString = ActivityID;
}
This all works when the row is selected however when i press my "btUpdate" button the ActivityIDString becomes NULL.
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
I understand the issue and why it becomes NULL but I don't know exactly how to solve this issue and where to use the ViewState.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ActivityIDStringText"] = "ActivityIDString"; // <-- SHOULD I CREATE THIS?????
}
}
this method should be something like this
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ViewState["ActivityIDString"] = ActivityID;
}
then retrieve it in button method
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string ActivityIDString= Convert.ToString(ViewState["ActivityIDString"]);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
You can use Session here. Whenever a row is selected add the ID in the session and retrieve the value of the session object in the btUpdate click event and then null the session .
Inside the gwActivity_RowCommand()
Session["ActivityId"] += ";ActivityId";
and inside btUpdate_Click()
if(Session["ActivityId"]!=null){
var ActivityIds = Session["ActivityId"].Split(';'); // For Mulitple Ids if Required
Session["ActivityId"] = null;
}

Fill a grid view by a drop down list

I have a drop down list ; a sqldatasource and a gridview .
I want to fill the grid view by the choice in the drop down list.
How can i implement this fill ?
Thanks
My question is not a duplicate of this Click
because it want to populate a drop down list inside the grid view instead my question is : by a choice of a drop down list , fill a grid view.
EDIT (Because i am in negative rep.) :
What i have tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
aspx page
<asp:DropDownList runat="server" ID="drp" AutoPostBack="true" OnSelectedIndexChanged="drp_SelectedIndexChanged"></asp:DropDownList>
<asp:GridView runat="server" ID="grd" AutoGenerateColumns="true"></asp:GridView>
code behind of aspx
protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
grd = dataSource;
grd.DataBind();
}
Bind grid on selection index change event of dropdown.

keep dataTable present through page navigating aspx.net

i have data Table which is dynamically created and is bind to grid View and the page have a button which is redirecting user on another page when is clicked. That's page one.Now when user is redirected on page 2, and if he want to get back on page 1, I want to be present data Table when page load.Some example code how to do that?
page1
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
public void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
//method for insert dataTable in database
public void Button2_Click(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"] = dtCurrentTable;
dtCurrentTable = (DataTable)Session["Markici"];
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
SqlCommand cmd = new SqlCommand("InsertMarkica",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertMarkica";
foreach (DataRow dr in dtCurrentTable.Rows)
{
cmd.Parameters.Clear();
//SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#FirmaID", dr["FirmaID"]);
cmd.Parameters.AddWithValue("#Godina", dr["Godina"]);
cmd.Parameters.AddWithValue("#Kasa", dr["KasaID"]);
cmd.Parameters.AddWithValue("#Masa", dr["Masa"]);
cmd.Parameters.AddWithValue("#MarkicaID", dr["MarkicaID"]);
cmd.Parameters.AddWithValue("#Datum", dr["Datum"]);
cmd.Parameters.AddWithValue("#VrabotenID", dr["VrabotenID"]);
cmd.Parameters.AddWithValue("#Smena", dr["Smena"]);
cmd.Parameters.AddWithValue("#VkIznos", dr["VkIznos"]);
cmd.Parameters.AddWithValue("#VkDanok", dr["VkDanok"]);
cmd.ExecuteNonQuery();
cmd.Connection = conn;
}
page2
public void Button2_Click(object sender, EventArgs e)
{
Reponse.Redirect("Page1.aspx");
//Now when is redirected on page1, it should be present data Tale,
//needed that data Table for inserting records in database
}
You can create a session variable as follow
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"]=dtCurrentTable;
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
Not the value of Session["Markici"] will be available in the current session on any page. You need to cast and use it as follow
dtCurrentTable = (DataTable)Session["Markici"];

Paging in Gridview not working 2nd page data not showing data?

my gridview
<div style="margin-left: 280px">
<asp:GridView ID="exportGrdVw" runat="server" BackColor="White"
AllowPaging="True" PageSize="3"
OnPageIndexChanging="exportGrdVw_PageIndexChanging"
onpageindexchanged="exportGrdVw_PageIndexChanged">
</asp:GridView>
</div>
my code
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
BindEmployee();
}
}
public void BindEmployee()
{
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
the problem is gridview is displaying but when i click page 2. 2nd page data is not showing (blank). pls help me to solve this problem.
see that the code is correct or not
Use like below
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployee();
}
}
public void BindEmployee()
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
Your datatable gets initialize in every page load so you need to get the datatable
everytime before binding it to grid.
Set your page Index before binding it to grid
So your code should be like this
public void BindEmployee(int newPageIndex = -1)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.PageIndex = newPageIndex;
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
No need to call database on exportGrdVw_PageIndexChanging. Just declare DataTable table as static
You can try this:
GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Emp_Data ORDER BY [ID] DESC", con);
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);
GridView1.DataSource = DT1;
GridView1.DataBind();

Grid view Updatearguments does Not contain New Values

public partial class Gridvw_expt2 : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
com = new SqlCommand("Select * from tblExpt",con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows[0] != null)
{
GridView1.AutoGenerateEditButton = true;
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
}
else
Response.Write("fkj");
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
foreach (DictionaryEntry entry in e.NewValues)
{
e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
}
com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
da = new SqlDataAdapter(com);
GridView1.EditIndex = -1;
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
In the above code when i try to access e.new values index out of range exception is thrown.
The table being accessed contains 3 fields id, class, name
Please help to solve the problem.
Read this blog post I wrote on extracting data from gridview (and other data controls). Also, in .net 4.0 if you use 2 way binding (<# Bind("") #>) e.NewValues will be populated.
More info here: http://weblogs.asp.net/davidfowler/archive/2008/12/12/getting-your-data-out-of-the-data-controls.aspx
The exception you get is because row.Cells[0].Controls[0] is a DataControlLinkButton and not a TextBox. Since I donĀ“t know the control layout of your grid you could search for your textbox instead.
Instead of:
int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);
do something like the code below if there is only one TextBox per row:
TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );
If you have nested html and hierarchies check out this SO question for nested searching of controls

Resources