GridView PageIndexChanging Not Working - c#

This seems to be an easy question to ask, but I am not able to show items in GridView. Here is my code:
public partial class TestList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ TestProject.DataAccess.Repository.Instance.Initialize(Settings.Default.TestConnection);
BindData();
}
}
private void BindData()
{
//Restriction Info!!
gvAgentList.DataSource = EntityRegistration.DataAccess.Repository.Instance.GetData();
gvAgentList.DataBind();
}
protected void gvAgentList_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
gvAgentList.PageIndex = e.NewPageIndex;
gvAgentList.DataBind();
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void gvAgentList_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gvAgentList.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gvAgentList.DataSource = dataView;
gvAgentList.DataBind();
}
}
}
Here is the markup of the GridView:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
Agent Lists:</p>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView runat ="server" ID = "gvAgentList"
AllowPaging = "True"
AutoGenerateSelectButton="True" AllowSorting="True" BackColor="#E8E8E8"
BorderColor="#003399" BorderStyle="Solid" BorderWidth="1px" Height="375px"
Width="731px" OnPageIndexChanging = "gvAgentList_PageIndexChanging"
OnSorting="gvAgentList_Sorting" >
<AlternatingRowStyle ForeColor="#0066CC" />
<HeaderStyle ForeColor="#3366FF" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The problem is that my GridView is not throwing me any exception and through breakpoints I can see that the function is called in code behind.
My sorting is also not working :(

Try
protected void gvAgentList_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
gvAgentList.PageIndex = e.NewPageIndex;
BindData();
}

Set pageindex property of gridview e.g. PageIndex="10"

Related

CheckBox Not Sending Checked Value to Database C# Asp

I am making a Attendance System in which I get Student Record from student table in a Gridview with a check box. tick the check box for students present and leave unchecked for absent.
After that i submit my record to attendance system.
Problem: If I Check or left unchecked it will show the Absent in Database Results after submission of attendance please check my code.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RecordTablesss.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelSr" runat="server" Text=<%#Eval("Sr_Number") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text=<%#Eval("Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelFN" runat="server" Text=<%#Eval("F_Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckAttendence" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="SaveAttendence" style="width: 61px" />
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace RecordTablesss
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadData();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void loadData()
{
SqlConnection con = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select Sr_Number,Name,F_Name From Registerd_Student",con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void SaveAttendence(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
string sta = "A";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
string StudentName = (row.FindControl("LabelName") as Label).Text;
string F_Name = (row.FindControl("LabelFN") as Label).Text;
int Number = int.Parse( (row.FindControl("LabelSr") as Label).Text);
//From Here to onword Database Operations. ..
SqlConnection conn = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into Attendance_B values('"+Convert.ToInt32(Number)+"','"+StudentName+"','"+F_Name+"','"+sta+"')",conn);
cmd.ExecuteNonQuery();
}
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
}
}
}
As You said #Thomas Krojer Answer also not solving your issue but it should do.
The resone you are getting chkVar_.Checked always false.because On Page_Load you are binding gridview again with out checking if it is a postback.
Try this.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadData();
}
}
It will solve your problem surely..
I think you do not really write what you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
sta = "A";
I thin you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}
you see the difference?
you just need to correct code
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}

Gridview paging using Datatable - not working

I have a gridview which has paging but when I click on Page 2 - page refreshes and returns the first page and the page link also remains on page 1.
Any help will be really appreciated :)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Sequence" HeaderText="Sequence" HeaderStyle-
Width="10%"/>
<asp:TemplateField HeaderStyle-Width="90%">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>' Font-
Strikeout='<%# ((Convert.ToBoolean(Eval("Obsolete")))?true:false) %>' />
</ItemTemplate>
</asp:TemplateField>
Codebehind:-
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID,
_criteria.ParentGUID, _criteria.ShowObsolete);
GridView1.PageSize = 20;
ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
PageIndexChanging:-
public void GridView1_PageIndexChanging(object
sender,GridViewPageEventArgse)
{
GridView x = ((GridView)sender);
GridView1.DataSource = ViewState["dt_data"];
if (e.NewPageIndex > -1 && e.NewPageIndex <= x.PageCount)
{
x.PageIndex = e.NewPageIndex+1;
}
else
{
e.NewPageIndex--;
}
GridView1.DataBind();
}
Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BuildResults();
}
}
modify PageIndexChanging code
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgse)
{
GridView1.DataSource = (DataTable)ViewState["dt_data"];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Set AllowPaging=”True” Properties of GridView to enable paging
Set PageSize property to mention how many records will be displayed on
each page.
HTML MARKUP :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="20"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID, _criteria.ParentGUID, _criteria.ShowObsolete);
// GridView1.PageSize = 20;
// ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BuildResults();
}
I had a Response.Write on the page elsewhere and this was causing the paging to fail - removed it and this now works

Error when paging in GridView

I have a GridView with two columns. The first shows a date and the second, the year of the date in the first column. So far everything works well but when I change page, the web fails with the message: "Object reference not set to an instance of an object."
This is my code:
Test.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="qq_site_Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TEST</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5"
AllowSorting="True" AutoGenerateColumns="False"
EnableModelValidation="True" onrowcreated="GridView1_RowCreated"
onpageindexchanged="GridView1_PageIndexChanged"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="creationDate" HeaderText="creationDate" SortExpression="creationDate" />
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Test.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.Data;
public partial class qq_site_Test : System.Web.UI.Page
{
static DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
String connectionString = "DSN=kitchenmaster.es.qq-site;";
String sqlQuery = "SELECT * FROM tblSystems WHERE ID < 100";
ds = new DataSet();
OdbcConnection connection = new OdbcConnection(connectionString);
OdbcCommand command = new OdbcCommand(sqlQuery, connection);
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
try
{
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected int GetColumnByID(String columnName)
{
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == columnName)
return GridView1.Columns.IndexOf(column);
}
return -1;
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedIndex = -1;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (e.NewPageIndex != -1)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
Can you help me?
This line of code
GridView1.DataSource = ds;
is probably where you are getting the error.
When the GridView1_PageIndexChanging event is called, you have not yet set the value for ds. The only part in your code that does so is in the Page_Load event, and only when it's not a postback.
If I check the value of the e.Row.DataItem in the event GridView1_RowCreated(), the error not occurs but I don't know if it's the right thing to do. The new version of the event is:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
if (e.Row.DataItem != null)
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
}
catch (System.Exception ex)
{
Response.Write("** " + ex.Message);
}
}
}
Please check your "ds" object inside in PageIndexChanging event.
First fill the data set and bind.

Gridview Paging ASP.NET with Pager Panel outside Gridview

This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>

Binding dropdownlist inside gridview edititemtemplate

I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.

Categories

Resources