I am assigning DataSource to GridView from server side and apply pagination but it doesn't working. I don't know what i am doing wrong Below is my Code.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
</asp:GridView>
Below is my Server side code.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
{
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;
this.BindGrid();
}
Related
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getControls();
}
}
public void getControls()
{
string connn = ConfigurationManager.ConnectionStrings["RiskRegisterDBConnectionString"].ConnectionString;
DataTable ds = DB.GetDataTable("Select * from ControlTable", connn);
// GridView11.DataSource = ds;
GridView11.DataBind();
}
I have tried using AutoGenerationColumn as "true" and "false" both, but I'm not getting the gridview to display in browser while running the program.
<asp:GridView ID="GridView11" runat="server"
AutogenerateColumns="False" Cellpadding="4"
CssClass="auto-style6" DataKeyNames="Control_ID"
DataSourceID="SqlDataSource1"
Forecolor="#333333" Gridlines="None" Width="1124px" >
Try you code say like this:
public void getControls()
{
string strCon =
ConfigurationManager.ConnectionStrings["RiskRegisterDBConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
string strSQL =
#"SELECT * FROM ControlTable";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
DataTable dt = new DataTable();
conn.Open();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
public partial class _Default : System.Web.UI.Page
{
protected void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#date1", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#date2", TextBox2.Text.ToString());
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblerror.Text = ex.Message.ToString();
}
finally
{
con.Close();
con.Dispose();
}
}
}
How to give paging in some sites they have given bind grid but if i used bind grid here i can't run it on submit button?
protected void reset_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
protected void save_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox check = (CheckBox)gvr.FindControl("check");
if (check.Checked)
{
conn.Open();
string data1 = ((Label)gvr.FindControl("pomas_pono")).Text;
string data2 = ((Label)gvr.FindControl("pomas_suppliercode")).Text;
string data3 = ((Label)gvr.FindControl("pomas_pobasicvalue")).Text;
string data4 = ((Label)gvr.FindControl("poitm_itemcode")).Text;
string data5 = ((Label)gvr.FindControl("poitm_order_quantity")).Text;
string data6 = ((Label)gvr.FindControl("poitm_itemvalue")).Text;
string data7 = ((Label)gvr.FindControl("poitm_itemdescription")).Text;
string data8 = ((TextBox)gvr.FindControl("remarks")).Text;
SqlCommand command = new SqlCommand("INSERT INTO po_remarks" + "(pomas_pono,pomas_suppliercode,pomas_pobasicvalue,poitm_itemcode,poitm_order_quantity,poitm_itemvalue,poitm_itemdescription,remarks) VALUES(#pomas_pono,#pomas_suppliercode,#pomas_pobasicvalue,#poitm_itemcode,#poitm_order_quantity,#poitm_itemvalue,#poitm_itemdescription,#remarks)", conn); //generate insert sql using above data
command.Parameters.AddWithValue("#pomas_pono", data1);
command.Parameters.AddWithValue("#pomas_suppliercode", data2);
command.Parameters.AddWithValue("#pomas_pobasicvalue", data3);
command.Parameters.AddWithValue("#poitm_itemcode", data4);
command.Parameters.AddWithValue("#poitm_order_quantity", data5);
command.Parameters.AddWithValue("#poitm_itemvalue", data6);
command.Parameters.AddWithValue("#poitm_itemdescription", data7);
command.Parameters.AddWithValue("#remarks", data8);
command.ExecuteNonQuery();
}
}
conn.Close();
}
protected void cancel_Click(object sender, EventArgs e)
{
Page.Response.Redirect("Default.aspx");
}
The GridView control has a paging option as described here: https://msdn.microsoft.com/en-us/library/aa479347.aspx
<asp:GridView ID=" productsGridView" Runat="server"
DataSourceID="productDataSource" AutoGenerateColumns="False"
AllowSorting="True" BorderWidth="2px" BackColor="White"
GridLines="None" CellPadding="3"
CellSpacing="1" BorderStyle="Ridge" BorderColor="White"
AllowPaging="True" PageSize=50>
Notice the property of: AllowPaging. You can specify the number of records per page using the PageSize property. I think the default PageSize is: 10.
You can also specify the properties programmatically e.g.
GridView1.AllowPaging=true;
GridView1.PageSize=50;
protected void submit_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}
I have two query's in C# running in a datagridview, one is to show all data. the other is set to display in the footer. The footer is showing, just not displaying my query.
query one (with footer)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
the datagrid shows query one works well, the footer even shows but it has not got any data.
Although you have it working, there are ways to improve it.
In the first method, using statement would manage the connection better:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
And the second method:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
Probably I would use GridView's RowDataBound to write into footer where I can can know the type of row:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
EDIT : Here's the markup I have used to test:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>
After hours of problems, I have solved it.
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
although I am sure there is a better way of doing this, if you know please feel free to edit.
I have a textbox where I write a word to search in the gridview. The research works well for the first page of my gridview, but when I go to another page the research resets.
Here is my code :
using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "select * from Ressources";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].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;
}
}
}
}
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
private void BindData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + ";select * from Ressources", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
...
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView1.EditIndex >= 0)
return;
if ((e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) &&
(e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header))
{
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].Visible = false;
e.Row.Cells[6].Visible = false;
e.Row.Cells[7].Visible = false;
e.Row.Cells[8].Visible = false;
e.Row.Cells[10].Visible = false;
e.Row.Cells[14].Visible = false;
e.Row.Cells[15].Visible = false;
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
...
}
private void AddNewRecord(string URL, string Type_Source, string First_date, string Data, string Crawler_subcategory)
{
...
}
protected void Button1_Click(object sender, EventArgs e)
{
...
}
public void btnSearch_Click(object sender, EventArgs e)
{
string query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
The function used to search the word is named btnSearch_Click().
I would appreciate your help.
Thank you !
I would use a dataview and rowfilter. You could also choose to cache the OriginalDataTable in a sessionvariable.
public partial class WebForm1 : System.Web.UI.Page
{
// Hold the original datatable from database
System.Data.DataTable OriginalDataTable = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridView("");
}
void BindGridView(string searchQuery )
{
GridView1.DataSource = GetSelectionResult(searchQuery);
GridView1.DataBind();
}
private void initialData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString;
string query = "select * from Ressources";
OriginalDataTable = new DataTable();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString))
{
dataAdapter.Fill(OriginalDataTable);
}
}
DataView GetSelectionResult(string searchParam)
{
if (OriginalDataTable == null)
initialData();
if (string.IsNullOrEmpty(searchParam))
return OriginalDataTable.DefaultView;
string rowFilter = string.Format("data like '%{0}%'", searchParam);
return new DataView(OriginalDataTable, rowFilter, "data", DataViewRowState.OriginalRows);
}
protected void Button1_Click(object sender, EventArgs e)
{
BindGridView(TextBox1.Text);
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
//...
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView(TextBox1.Text);
}
}
In the case of caching the datatable into a sessionvariable:
private void initialData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString;
string query = "select * from Ressources";
if (Session["datatableinsession"] == null)
{
OriginalDataTable = new DataTable();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString))
{
dataAdapter.Fill(OriginalDataTable);
}
}
else
{
OriginalDataTable = Session["datatableinsession"] as DataTable;
}
}
Regards.
public void btnSearch_Click(object sender, EventArgs e)
{
BindData();
}
Private xxx BindData()
{
if(Viewstate[txt] !==null)
{
string WhereCl= GetWhereClause(txt);
}
string query = "select * from Ressources";
if(!string.IsNullOrEmpty(WhereCl))
{
query =query + WhereCl;
}
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Private string GetWhereClause(string txt)
{
string where = where data like'%" + txt+ "%'";
}
Call this binding method on paging also .
Hope this helps ..
isn't it faster to just save the search parameter in session, check if it is inside and search it again (since it seems your text data isn't saved)
Declare separate method as
private void Search()
{
string query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Call Search() on page index chenging as
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Search();
}
And you can call the same method on search button click.
public void btnSearch_Click(object sender, EventArgs e)
{
Search();
}
Create only one Method to Bind The Data as below:
private void BindData()
{
string query = "";
if (txtSearch.Text != "" && txtSearch.Text != string.Empty) {
query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
} else {
query = "select * from Ressources";
}
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Thats all