I have a webform set up with a button click that parses a .txt file and puts it in a datatable. when the parsing ends the datatable is bound to the gridview. I tried to add paging since I get tons of rows but it does not seem to work properly. Whenever I click on the next page the grid disappears and for it to appear again on the correct page I need to click on the button again.
I tried adding the following code to the source :
<asp:GridView ID="GridView1" Runat="server"
AutoGenerateColumns="true"
AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" >
and this bit :
protected void OnPageIndexChanging(object sender, EventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
but it doesn't seem to change anything. Any idea on what I'm doing wrong?
Try to Add OnPageIndexChanging Event inside GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="5">
and your aspx.cs code. Try to Bind Gridview on Page_Load Event.
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{ this.BindGrid();}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * From [dbo].[your table] "))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//here yo have to assign datasource
//Some thing like this
///GridView1.DataSource=DataTable;
GridView1.DataBind();
}
Related
I'm currently using ASP.net and C#. I want to add an "Edit" button to my grid view, but I don't know how can I add a command on the button. And I also would gladly welcome any suggestions on how I can enhance this gridview.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null)
{
Response.Redirect("~/LoginPage.aspx");
}
lbl_name.Text = "Welcome :: " + Session["username"];
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT product_name,product_price,product_desc,product_stock FROM product_tbl";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "user_tbl");
GridView1.DataSource = ds.Tables["user_tbl"];
GridView1.DataBind();
}
catch (Exception ex)
{
lbl_result.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
}
You can use RowCommand Event in GridView. The RowCommand Event occurs when a button is clicked in a GridView control. See this
You can add a CommandField with the Edit button:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="GridView1_RowEditing" ...>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowCancelButton="true" />
....
</asp:GridView>
And process the RowEditing event:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ...
GridView1.DataBind();
}
More details are given here: ASP.NET GridView: How to edit and delete data records.
I have a GridView containing data extracted from two TextBoxes on click of a button. I want the following functionalities to be implemented in the Gridview:
1) I want to be able to Edit the data in this GridView.
2) I should also be able to Delete the rows from the GridView.
3) Finally, when I click on another Submit button, all the rows from the Gridview should be saved in the database.
Its a web-based ASP.NET application coded using C# (Visual Studio 2010), and uses SQL Server 2005. How can I make changes to the below code to implement the above specified functionality?
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
Session["data_table"] = dt;
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
ds.Clear();
da = new SqlDataAdapter("insert into PRACT values(#name, #city)", con);
con.Open();
da.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
con.Close();
}
}
Well on your aspx page I would recommend you to do that:
<asp:GridView runat="server" id="gvDisplay" OnRowCommand="grid_OnRowCommand">
<Columns>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtNameGrid" Text='<%#DataBinder.Eval(Container.DataItem, "Name")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtCityGrid" Text='<%#DataBinder.Eval(Container.DataItem, "City")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:Button runat="server" id="btnDeleteGrid" Text = "Delete" CommandArgument='<%#Eval(Container.DataItem, "YourIDColumn")%>' CommandName="DeleteRow"/>
</ItemTemplate>
</TemplateField>
</Columns>
</asp:GridView>
I recommend you to create a new column in your DataTable, this column will be the ID of each register.
Well, you add registers to this DataTable on your page, so you will need to create a session of type int and each time the event btnTextDisplay_Click is called you must increase this int Session and set it's value to the DataTable's Column ID.
The grid's attribute, OnRowCommand, is the event that will be called when you click on the button btnDeleteGrid. The code of this event comes below:
protected void grid_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "DeleteRow")
{
foreach(DataRow row in dt.Rows)
{
if(Convert.ToInt32(row["YourColumnID"]) == Convert.ToInt32(e.CommandArgument))
row.Delete();
}
dt.AcceptChanges();
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
Your event that will save the registers should be like that.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach(DataRow row in dt.Rows)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO YOUR_TABLE_NAME (NAME, CITY) VALUES (" + row["Name"].ToString() + "," + row["City"].ToString() + ")";
int numRegs = cmd.ExecuteNonQuery();
}
}
I really expect I helped.
I can't test my code and I'm not so good on work with DataTables, so if there's any problem with my code, just let me know.
I think it will be more efficient if you use Bulk Inserts to realize the inserts. Search for how to make it, it's pretty cool and quick.
And also try to use Stored Procedures, because it's safer than use direct command texts. Using them will prevent SQL Injection.
Best regards.
Gridview: Data does not change on page change.
Hi, im working on a asp.net website with c#.
I have a gridview with paging, the gridview is populated from an sql database, and on the PageIndexChanging I have:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl();
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
If I click on page 2 for example, the next rows of data display fine.
But if I click back to the page 1, the data does not change, it keep displaying the data from the page 2.
How can I solve this?
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}
Is your BindGridControl() load the data and set it to your gridView datasource?
You can reverse order of instructions
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
gridView.DataBind();
}
I had this problem too for a long time.
I came up with this and it finally works for me.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindGridControl(e.NewPageIndex);
}
And then in your BindGridControl function:
protected void BindGridControl(int pageNumber = 0)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[connection].ConnectionString);
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_load";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.PageIndex = pageNumber;
GridView1.DataSource = dt;
GridView1.DataBind();
sqlConn.Close();
}
Try
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
BindGridControl();
DataBind();
}
I have made AllowPaging to True in formview .It is showing the link buttons but they are not working(obviously they need a function to execute).I have OnPageIndexChangeing event like Below .Can you please tell how to jump to next page and make the pager working.I am bind the Form view using sp in Page_Load event.
Aspx code:
<asp:FormView ID="form_view_with_sp" runat="server" OnModeChanging="mode_changeing" OnPageIndexChanging="page_index_chaging" AllowPaging="true">
page_index_changing event:-
protected void page_index_chaging(object sender, FormViewPageEventArgs e)
{
}
Page_Load:-
SqlConnection con = new SqlConnection(getconnectionstring());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "selectprocedure";
DataTable dt = new DataTable();
cmd.Connection = con;
con.Open();
SqlDataAdapter adb = new SqlDataAdapter("selectprocedure", con);
form_view_with_sp.DataSource = dt;
form_view_with_sp.DataBind();
Thanks in advance.
You will need to assign the DataSource of the FormView in the page_index_chaging event handler. Please try to use the following
protected void page_index_chaging(object sender, FormViewPageEventArgs e)
{
DataTable dt = (DataTable)ViewState["DataSource"];
form_view_with_sp.DataSource = dt;
form_view_with_sp.DataBind();
}
Remember to put the DataTable into ViewState in Page_Load event when creating the DataSource.
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(abc);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(bc);
}
else
Response.Write("fkj");
}
protected void abc(object sender, GridViewUpdateEventArgs e)
{
Response.Write(e.RowIndex);
}
protected void bc(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = e.NewEditIndex;
}
}
the row used to get in edit mode only if i edit the next row means first row never get in edited mode.Please help why so.
Istead of
GridView1.Attributes.Add("onrowupdating", "abc");
do this:
GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
Also, Instead of
GridView1.Attributes.Add("DataKeyNames", "id");
do this
GridView1.DataKeyNames = new string[] { "id" };
Also x 2, Instead of
if (ds.Tables[0].Rows[0].ToString() != null)
do this
if (ds.Tables[0].Rows[0] != null) //.ToString() will cause an exception if it is actuall null
Why do I feel like I am teaching a class :)
Its because you haven't set up a handler to handle GridView.RowEditing. On your gridview (in the .aspx) you need to wire up a method which will deal with RowEditing.
You're gridview code will look like:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
You need to add:
OnRowEditing="nameOfMethodYouWantToFire"
so it looks like:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="nameOfMethodYouWantToFire">
</asp:GridView>
Where nameOfMethodYouWantToFire is in your code behind (your C#) and it handles the event. Something like this:
protected void nameOfMethodYouWantToFire(object sender, GridViewPageEventArgs e)
{
//Your code here
}