I have a DataGridView on a page. When I call that page whole list comes. I have decided to add pagination to the GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_Del" OnSelectedIndexChanging="GridView1_Sel" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id" Visible="false" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="author" HeaderText="Author" SortExpression="author" />
<asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" />
<asp:CommandField HeaderText="Delete" SelectText="Delete" ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill() method fills the GridView.
public void gridFill()
{
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/inetpub/example.com/db/db.mdb");
sql = "SELECT id, name, author, active, FROM [table]";
dt = new DataTable();
try
{
if (conn.State != ConnectionState.Open) conn.Open();
comm= new OleDbCommand(sql, conn);
da= new OleDbDataAdapter(comm);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
catch (System.Data.OleDb.OleDbException ex)
{
string msg = "Error: ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
When I call the page it still gets all the rows at once. Also if I click 11th or later (because I limit the paging to 10 rows) rows for deleting I get index error.
So I have added another Button labeled as 'Refresh' which calls gridFill() method once more. Then pagination gets valid.
What could be the reason for GridView not paging for the first time?
If I change the order of the lines
//Page_Load()
gridFill();
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
to
//Page_Load()
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
gridFill();
it works. I can't believe it
Related
I have problem when add information about total pages and total rows in footer gridview,
This my Html code;
<asp:GridView ID="GridView1" runat="server"
onpageindexchanging="GridView1_PageIndexChanging" AllowPaging="True"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" AutoGenerateColumns="False" Width="500px">
<Columns>
<asp:BoundField HeaderText="ProductId" DataField="ProductId" >
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductName" DataField="ProductName">
<ItemStyle Width="300px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="SupplierId" DataField="SupplierId">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" PageButtonCount="7" Mode="NumericFirstLast" />
<RowStyle ForeColor="#000066" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
This aspx code:
public void BindData()
{
string strConnection = #"Data Source=.\sa;Initial Catalog=Northwind;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select ProductId, ProductName, SupplierId from Products", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
//Script row 10
int rowcount = ds.Tables[0].Rows.Count;
int remainingCount = 10 - (rowcount % 10);
for (int i = 0; i < remainingCount; i++)
{
DataRow row = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(row);
}
//Script row ~10
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
My gridview
This my problem, I didnt find a way to add information total pages and rows
anybody can improve my code.
call this in your binding method
int TotalRecord = ds.Rows.Count(); //This is total number of records in gridview
GridView1.DataSource = ds;
GridView1.DataBind();
you can later call that Totalrecord in a label or something u want to be in your gridview refer here as well:https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridviewrowcollection.count?view=netframework-4.8
I am using radio button inside gridivew. I want to select 1 radio button at a time not multiple. I tried this but not working i.e it disables the only selected one too.
protected void btnAward_CheckedChanged(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in gvAppliedWorks.Rows)
{
int RowIndex = gr.RowIndex;
int AppliedWorkID = gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
RadioButton rdbtn = gr.FindControl("btnAward") as RadioButton;
if (rdbtn.Checked == true)
{
//if(RowIndex )
rdbtn.Checked = false;
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
}
Try this code:
GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" id="rbtn1" name="rbtn" GroupName="rgrp" onclick = "RadioCheck(this);" ></asp:RadioButton>
<asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code for filling gridview from DB
protected void bind()
{
using (SqlConnection con = new SqlConnection("Connection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tableName", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
Finally add this script to avoid multiple selection
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
I have a gridview that loads data from database. The data is displayed in the gridview for the first time sorted by datetime. On one column of that gridview I want to allow sorting, for example on the main_post column. I had tried this, but the gridview still did not sort when I click the header of the column.
This is my front-end code for gridview:
<asp:DataGrid ID="Datagrid1" runat="server"
AllowPaging="True"
AllowSorting="True"
OnSorting="ComponentGridView_Sorting">
<Columns>
<asp:BoundColumn DataField="main_post" HeaderText="Header Post ID"
SortExpression="ComponentGridView_Sorting" />
</Columns>
</asp:DataGrid>
My back-end code:
protected void loadData()
{
DataTable dtTemp;
dtTemp = objDBInterface.getResults(strSQL);
Datagrid1.DataSource = dtTemp;
Datagrid1.DataBind();
ViewState["dtbl"] = dtTemp;
}
protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ViewState["dtbl"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
Datagrid1.DataSource = dataView;
Datagrid1.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
I dont have any error and I dont know where my mistake is, could somebody please help me to solve this problem?
Thanks in advance.
Simple, set Allowsorting property true and add sorting event in your gridview.
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
OnSorting="GridView1_Sorting">
</asp:GridView>
Now add Event OnSorting in .cs file
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDireaction);
if (dataTable != null)
{
dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection;
GridView1.DataSource = dataTable;
GridView1.DataBind();
SortDireaction = _sortDirection;
}
}
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
{
_sortDirection = "DESC";
}
else
{
_sortDirection = "ASC";
}
}
I got the solution. Hope this will help others people that face this similar problem. On .aspx page need to change:
from OnSorting="ComponentGridView_Sorting"
to onsortcommand="ComponentGridView_Sorting"
Then put this code on aspx.cs(back-end code):
protected void Datagrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
{
string strSQL;
DataTable dt;
strSQL = "YOUR SELECT STATEMENT (SQL)";
dt = strSQL;
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
Datagrid1.DataSource = sortedView;
Datagrid1.DataBind();
}
}
protected SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
Do not take tension developers it's really too easy follow my steps
Step 1 Create GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" class="w3-table-all"
OnPageIndexChanging="OnPageIndexChanging" PageSize="20" >
<Columns>
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="250px" DataField="sn_no" HeaderText="ID" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="name" HeaderText="Name" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="mo" HeaderText="Mobile" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="email" HeaderText="Email Id" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="loc" HeaderText="Location" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="day2" HeaderText="Day" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
<asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="time" HeaderText="Time" />
</Columns>
</asp:GridView>
Step 2 Goto *.aspx.cs file and write
a). For descending order
cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no DESC", con);
b). For ascending order
cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no ASC", con);
Thanks with love #Vaibhav Yadav
Vaibhav Designs
http://vaibhavdesigns.org
for more ...
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="empid" DataSourceID="SqlDataSource1" EnableModelValidation="True" ForeColor="#333333" GridLines="None">
I am binding the gridview and showing their corresponding total in footer without any error. Now I want to add extra runs as below highlighted in image(which is completely discrete datarow and it does not belong to dataset).I want to achieve functionality like below Image.
Here is my code :
<asp:GridView ID="gvFirstInningBatting" runat="server" AllowSorting="True" AutoGenerateColumns="false"
GridLines="None" AllowPaging="false" CellPadding="4" CssClass="GridViewStyle" OnRowDataBound="gvFirstInningBatting_RowDataBound"
ShowFooter="true" ShowHeader="true" Width="100%">
<Columns>
<asp:BoundField DataField="P_PlayerPopulerName" HeaderText="Batting" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_PlayerStatus" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_RunsScored" HeaderText="R" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_MinutesBatted" HeaderText="M" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_BallsPlayed" HeaderText="B" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Fours" HeaderText="4s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Sixes" HeaderText="6s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_StrikeRate" HeaderText="SR" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
</Columns>
</asp:GridView>
In C#
protected void BindGridView(int scheduleId)
{
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_NAME", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
dBConnection.Open();
DataSet ds = new DataSet();
DataTable dtBatting = new DataTable();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(ds);
int gvBattingCount = Convert.ToInt32(cmd.Parameters["#BattingRowsCount"].Value);
for (int i = 0; i < gvBattingCount; i++)
{
if (ds.Tables[i].Rows.Count > 0)
{
if (i == 0)
{
DataRow dr1st;
ds.Tables[i].DefaultView.RowFilter = "SBTS_PlayerIsBatted = 1";
dtBatting = ds.Tables[i].DefaultView.ToTable();
dr1st = dtBatting.NewRow();
dr1st["P_PlayerPopulerName"] = " ";
dr1st["SBTS_RunsScored"] = 36;
dr1st["SBTS_PlayerStatus"] = "Extras";
dr1st["SBTS_MinutesBatted"] = 0;
dr1st["SBTS_BallsPlayed"] = 0;
dr1st["SBTS_Fours"] = 0;
dr1st["SBTS_Sixes"] = 0;
dr1st["SBTS_StrikeRate"] = 0;
dtBatting.Rows.Add(dr1st);
gvFirstInningBatting.DataSource = dtBatting;
gvFirstInningBatting.DataBind();
}
}
}
}
the grid is working if I use dr1st["SBTS_Sixes"] = 0; but it shows 0 in the row and if I use dr1st["SBTS_Sixes"] = DBNull.Value; then it is throwing error
Object cannot be cast from DBNull to other types.
What should I do, Please help me out.
I can't seem to get my code to work.
It's a simple application to populate an asp.net GridView control.
The grid control is not getting populated and I am not getting an error message.
What am I missing here?
Codebehind
public void DisconnectedDataform()
{
try
{
Initdata();
gvProjectList.DataSource = dsProjectList;
gvProjectList.DataMember = tableName;
}
catch (Exception e)
{
Response.Write(e.ToString());
}
finally
{ }
}
public void Initdata()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["dbProjectManager"].ConnectionString;
dsProjectList = new DataSet();
daProjectList = new SqlDataAdapter("select PersonID, FirstName, LastName from Person", conn);
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daProjectList);
daProjectList.Fill(dsProjectList, "ProjectList");
}
catch (Exception e)
{
Response.Write(e.ToString());
}
finally
{ }
}
ASPX code:
<asp:GridView ID="gvProjectList" runat="server" AutoGenerateColumns="true" DataKeyNames="PersonID">
<Columns>
<asp:BoundField DataField="PersonID" HeaderText="PersonID" InsertVisible="False" ReadOnly="True" SortExpression="PersonID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
</Columns>
</asp:GridView>
after setting the datasource try
gvProjectList.DataBind();