Gridview datasource is null after postback - c#

I have a page with a gridview that show article groups,and textbox and search button for search groups.
in this page if user not search anything ,grid view only show main groups(with parentId 0)
and else show every group that group name's contain textbox value.
My problem is when I search ,and then I want to update some row,GridView1_RowUpdating not fired...
I found that the problem is that gridview datasource not bound successfully.
how I fix this problem?
below is my source:
<asp:Label ID="Label1" runat="server" CssClass="txt" Text="searchgroups " ForeColor="#68a2d7"></asp:Label>
<asp:Label ID="Label2" runat="server" CssClass="txt" Text="group name" ForeColor="#68a2d7"></asp:Label>
<asp:TextBox ID="txtname" runat="server" CssClass="txt" Width="300px"></asp:TextBox>
<br/>
<asp:ImageButton ID="Ibtnsearch" runat="server" ImageAlign="Left" ImageUrl="../Icon/resize/search.gif"
OnClick="Ibtnsearch_Click" />
<br/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" Width="100%" CssClass="txt" AllowPaging="True"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowCommand="GridView1_RowCommand1" PageSize="15" AllowSorting="True" OnSorting="GridView1_Sorting">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="chid" SortExpression="chid" HeaderText="ID" />
<asp:BoundField DataField="chname" SortExpression="chname" HeaderText="Name" />
<asp:HyperLinkField DataNavigateUrlFields="chid,cLanguage" DataNavigateUrlFormatString="../default.aspx?pnl=lstcatChat&nParentid_fk={0}&lang={1}"
Text="Sub Groups" HeaderText="Show Sub Grups">
<ControlStyle CssClass="link" />
</asp:HyperLinkField>
<asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
EditText="Edit" HeaderText="Edit" />
</Columns>
<RowStyle BackColor="#e8edf2" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="White" ForeColor="#333333" HorizontalAlign="Center" BorderColor="White"
Font-Bold="True" Font-Names="Tahoma" Font-Overline="False" Font-Size="X-Small"
Font-Underline="False" />
<HeaderStyle BackColor="#68a2d7" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" />
<PagerSettings Mode="NumericFirstLast" />
</asp:GridView>
and in my code page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = Search_groups();
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = -1;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gvr = GridView1.Rows[e.RowIndex];
using (_Category nc = new _Category())
{
if (Request["lang"] == "" || Request["lang"] == null)
nc.Language = "fa";
else
nc.Language = Request["lang"];
DataTable dt2 = new DataTable();
dt2 = Search_groups();
int ncid = (int)dt2.Rows[e.RowIndex]["chid"];
ncid = Convert.ToInt32(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text);
nc.ID = ncid;
nc.Name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
nc.Updatefast();
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.EditIndex = -1;
GridView1.DataBind();
dt2.Dispose();
gvr.Dispose();
}
}
protected void Ibtnsearch_Click(object sender, ImageClickEventArgs e)
{
GridView1.DataSource = Search_groups();
if (GridViewSortExpresion != null && GridViewSortExpresion != "")
SortGridView(GridViewSortExpresion, GridViewSortDirection);
GridView1.DataBind();
}
private DataTable Search_groups()
{
if (Request["nParentid_fk"] != null)
parent_fk = Convert.ToInt32(Request["nParentid_fk"]);
else
parent_fk = 0;
using (_Category nc = new _Category())
{
if (Request["lang"] == "" || Request["lang"] == null)
nc.Language = "fa";
else
nc.Language = Request["lang"];
if (txtname.Text != "")
return nc.search_allcategories(txtname.Text);
else
return nc.Select_parentid_fk(parent_fk);
}
}
public string GridViewSortDirection
{
get
{
//if (ViewState["sortDirection"] == null)
// ViewState["sortDirection"] = SortDirection.Ascending;
//return (SortDirection)ViewState["sortDirection"];
if (SortDirection.Value == null)
SortDirection.Value = "asc";
return SortDirection.Value;
}
set { SortDirection.Value = value; }
}
public string GridViewSortExpresion
{
get
{
//if (ViewState["SortExpresion"] == null)
// ViewState["SortExpresion"] = "";
//if (ViewState["SortExpresion"] != null)
// return ViewState["SortExpresion"].ToString();
//else
// return null;
if (SortExpresion.Value != null)
return SortExpresion.Value.ToString();
else
return null;
}
set { SortExpresion.Value = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//DataTable dataTable = GridView1.DataSource as DataTable;
GridViewSortExpresion = e.SortExpression;
if (GridViewSortDirection == "asc")
{
GridViewSortDirection = "desc";
SortGridView(GridViewSortExpresion, GridViewSortDirection);
}
else
{
GridViewSortDirection = "asc";
SortGridView(GridViewSortExpresion, GridViewSortDirection);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
//DataTable dt = GridView1.DataSource as DataTable;
DataTable dt = Search_groups();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + " " + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
when I try to update ,I get this error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Edit 2
Now I found that my problem is that gridview loses datasource on post back ,
I search but I not found solution.I don't want to use session or viewstate,because I have a lot of tables like above ,What is the solution?

set following property:
set AutoGenerateEditButton="False"
Try putting:
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="btnEdit" runat="server" commandname="Edit" text="Edit" />
<asp:Button id="btnDelete" runat="server" commandname="Delete" text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button id="btnUpdate" runat="server" commandname="Update" text="Update" />
<asp:Button id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
In place of :
<asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
EditText="Edit" HeaderText="Edit" />

Related

Search btn with paging in grid view

I have created gridview with paging and search a data within gridview.I have number of data and number of page if u filter data in gridview it successfully display result with paging. After display i will click on next page because gridview will display only 10 records per page but i have more than 10 records which i have filtered so it will display page wise. Then when i click next page gridview will loads whole data from database and display but i want display only filtered record while searching data.
the aspx code is below
<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
<asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
<AlternatingRowStyle BackColor="#D4EFFD" />
<PagerSettings Position="Top" />
<PagerStyle Height="8px" HorizontalAlign="Center" />
<PagerTemplate>
<table align="center" style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center" style="width: 60%;">
<table align="center" width="50%">
<tr>
<td>
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style=" width: 8%;">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and aspx.cs code is below
protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
try
{
if (txtsearch.Text != "")
{
if (ViewState["data"] != null)
{
DataTable dt = (DataTable)ViewState["data"];
DataView dv = new DataView(dt);
dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
ViewState["filter"] = dv;
gvEdit.DataSource = dv;
gvEdit.DataBind();
//gvformlist.DataSource = dv;
//gvformlist.DataBind();
}
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
protected void Reset_Click(object sender, EventArgs e)
{
txtsearch.Text = "";
gvEdit.DataSource = ViewState["data"];
gvEdit.DataBind();
//gvformlist.DataSource = ViewState["data"];
//gvformlist.DataBind();
}
protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//gvEdit.PageIndex = e.NewPageIndex;
//gvformlist.PageIndex = e.NewPageIndex;
LoadFormList();
}
protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow pagerRow = gvEdit.TopPagerRow;
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (e.Row.RowType == DataControlRowType.Pager)
{
pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
}
}
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
{
// to Get No of pages and Page Navigation
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
+ gridView.PageCount.ToString();
Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
lblpageindx.Text += strPgeIndx;
}
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
LoadFormList();
}
protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
}
}
protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
I have changed code in gvEdit_PageIndexChanging as per someone suggestion code is below
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (ViewState["filter"] != null)
{
gvEdit.PageIndex = e.NewPageIndex;
gvEdit.DataSource = ViewState["filter"];
gvEdit.DataBind();
}
else
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
after that i run the code and i am getting error
error is System.Runtime.Serialization.SerializationException: Type 'System.Data.DataView' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
According to your question I try to give an answer. If you find my answer useful then mark is as answer or vote it up.
What I have done in below code is when user click on search button without input any student name it shows per page 10 records of all students and if you search by name it shows only specific students with paging. In below code I use a stored procedure and in that I put three parameters such as following:
#startRowIndex int
#pageSize int
#studentname varchar(50) = NULL
Default.aspx markup:
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>Gridview Pagging</td>
</tr>
<tr>
<td>
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div>
<asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
<asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
</Columns>
<EmptyDataRowStyle CssClass="emptyrow" />
<HeaderStyle CssClass="headerstyle2" />
<FooterStyle CssClass="footerstyle"></FooterStyle>
<EditRowStyle CssClass="editrowstyle"></EditRowStyle>
<SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
</asp:GridView>
</div>
<div style="margin-top: 20px; margin-bottom: 70px;" align="center">
<asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
OnCommand="ChangePage" Visible="False" />
<asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
Visible="False" />
<br />
<br />
<asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
<asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
<asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
<asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Default.aspx.cs code:
#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion
#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["startRowIndex"] = 0;
ViewState["currentPageNumber"] = 0;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
ViewState["currentPageNumber"] = 1;
ViewState["startRowIndex"] = 0;
break;
case "Previous":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;
break;
case "Next":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;
break;
case "Last":
ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
ViewState["currentPageNumber"] = lbltotalPages.Text;
break;
}
this.fillgridview();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
fillgridview();
}
#endregion
#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
DataSet dataset;
try
{
con = new SqlConnection(conquery);
SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
cmd.Parameters.AddWithValue("#startRowIndex", RowIndex);
cmd.Parameters.AddWithValue("#pageSize", Pagesize);
cmd.Parameters.AddWithValue("#studentname", studentname);
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
dataset = new DataSet();
da.Fill(dataset);
}
return dataset;
}
catch (SqlException ex)
{
return dataset = null;
}
}
private void fillgridview()
{
DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
if (newds.Tables.Count == 0)
{
return;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblCurrentPage.Visible = true;
lbltotalPages.Visible = true;
lblPageText1.Visible = true;
lblPageText2.Visible = true;
ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
newds.Tables[1].Rows.Clear();
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
{
ViewState["currentPageNumber"] = 1;
}
setPages();
this.gv.Visible = true;
this.gv.DataSource = newds.Tables[0];
this.gv.DataBind();
}
}
private void setPages()
{
lbltotalPages.Text = "";
lblCurrentPage.Text = "";
try
{
lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());
if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
else
{
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
if (int.Parse(lbltotalPages.Text) > 0)
{
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
}
else
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
}
if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
}
catch (Exception ex)
{
}
}
private int CalculateTotalPages(double totalrows)
{
return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion
first set enablepagingandcallback = false in gridview , then add
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
GridView1.DataBind();
}

Why buttonfield is not working ?

I am have put buttonfield in gridview. It hit the rowcommand event and goes to the end of block but doesn't do what it is supposed to do. It is supposed to assign text to the text box and shows message via response.write but doesn't. In debugger it perfectly assign text to the textbox and goes to the message but nothing on interface side. Why ?
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
event:
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
btnAddContractorType.Visible = false;
btnUpdate.Visible = true;
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
DataRow r = dt.Rows[0];
txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
Response.Write("DONE");
}
}
catch (Exception)
{
}
}
It doesn't do anything, apparently but shows and assigns in debugger. Why ?
Try adding OnRowEditing to your grid.
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowEditing="grdviewContractorTypes_RowEditing" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
Code Behind:
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
//btnAddContractorType.Visible = false;
//btnUpdate.Visible = true;
//DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
//DataRow r = dt.Rows[0];
//txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
Response.Write("DONE");
}
}
catch (Exception)
{
}
}
protected void grdviewContractorTypes_RowEditing(object sender, GridViewEditEventArgs e)
{
// code to edit
}

Gridview Paging is not working when i use it in content place holder?

I dont know why paging is not working when i use master page. If I put the same code in another file which in not linked with master page it works like a charm. But when I link it to master page it doesn't work.
here is my mark up
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="menu_content">
<div class="tabs">
My Addresses</div>
<div class="midContent">
<asp:GridView ID="addressGrd" OnPageIndexChanging="addressGrd_PageIndexChanging"
Width="816px" ForeColor="#ffffff" AllowSorting="true" HeaderStyle-BackColor="#222222"
HeaderStyle-Height="60px" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="True" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last"
PagerSettings-Mode="NextPreviousFirstLast" PageSize="5" PagerSettings-PageButtonCount="4">
<Columns>
<asp:BoundField DataField="customerName" HeaderText="Name" ReadOnly="True" />
<asp:BoundField DataField="customerCompany" HeaderText="Company" ReadOnly="True" />
<asp:BoundField DataField="customerPhone" HeaderText="Phone" ReadOnly="True" />
<asp:BoundField DataField="addressLine1" HeaderText="Address 1" ReadOnly="True" />
<asp:BoundField DataField="addressLine2" HeaderText="Address 2" ReadOnly="True" />
<asp:BoundField DataField="city" HeaderText="City" ReadOnly="True" />
<asp:BoundField DataField="state" HeaderText="State" ReadOnly="True" />
<asp:BoundField DataField="zipCode" HeaderText="Zip Code" ReadOnly="True" />
<asp:TemplateField>
<HeaderTemplate>
Main Address
</HeaderTemplate>
<ItemTemplate>
<asp:ImageButton runat="server" OnClick="changeStatus" ID="imgStatus" CommandArgument='<%#Eval("mainAddress")+","+ Eval("addressID")%>'
ImageUrl='<%# Bind_Image(Eval("mainAddress").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Action
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="editItem" Text=" " OnClick="Edit" CommandArgument='<%# Eval("addressID")%>'
CssClass="editButton" runat="server">
</asp:LinkButton>
<asp:LinkButton Text=" " ID="deleteItem" CssClass="deleteButton"
runat="server" CommandArgument='<%# Eval("addressID")%>' OnClientClick="return confirm('Do You Want To Delete ?')"
OnClick="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First"
LastPageText="Last" />
<PagerStyle BackColor="#222222" Height="30px" VerticalAlign="Bottom" HorizontalAlign="Center" />
<RowStyle Height="50px" BackColor="#117186" />
<AlternatingRowStyle BackColor="#0b4d5b" />
</asp:GridView>
<div style="float:right; margin-bottom:20px; margin-right:20px"><input type="button" class="buttonEffect" value="Register New Address" /></div>
</div>
</div>
and here is my code behind.
retrievedata3ct rd3ct;
DataTable dt;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
rd3ct = new retrievedata3ct();
dt = new DataTable();
ds = new DataSet();
if (!this.IsPostBack)
{
addAddresses();
}
}
public void addAddresses()
{
rd3ct = new retrievedata3ct();
ds = new DataSet();
ds = rd3ct.addressesSelection("", "");
addressGrd.DataSource = ds.Tables[0];
addressGrd.DataBind();
addressGrd.Visible = true;
//ScriptManager.GetCurrent(this).RegisterPostBackControl(addressGrd);
}
public string Bind_Image(string Status)
{
bool status = Convert.ToBoolean(Status);
if (status)
{
return "adminCP/resources/images/icons/tick_circle.png";
}
else
{
return "adminCP/resources/images/icons/cross_circle.png";
}
}
protected void addressGrd_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
addressGrd.PageIndex = e.NewPageIndex;
addAddresses();
}
protected void Delete(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
string ds = "";
ds = rd3ct.addressesDeletion(lnkRemove.CommandArgument);
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record Deleted.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
protected void Edit(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
Session["addressID"] = "";
Session["addressID"] = lnkRemove.CommandArgument;
Response.Redirect("editAddresses.php5", false);
}
protected void changeStatus(object sender, EventArgs e)
{
string ds = "";
ImageButton ib = (ImageButton)sender;
string[] commandArgs = ib.CommandArgument.ToString().Split(new char[] { ',' });
string status = commandArgs[0];
string id = commandArgs[1];
if (status == "True")
{
ds = rd3ct.addressesStatusUpdate(id, "False");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Disabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
else
{
ds = rd3ct.addressesStatusUpdate(id, "True");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Enabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
}
Please help me out. Any help would be highly appreciated.
Have you tried to create an empty master page to put the content into? I suspect your master page is breaking the GridView.
Problem Solved.
Actually button name was conflicting in grid view.
I was having a button and its ID was 'submit' and in my another page there was also a button named with the same ID. thats why gridview paging was not working.
R.I.P Coding.. :)

Can't get value from radio button on gridview on C#

Hello i have a Gridview with 4 radio buttons and i want to get the value from them, and no matter what i do the value is always false, could someone tellme where is my mistake?
This is the code of the gridview:
<asp:GridView ID="GridView8" runat="server" Width="903px"
Height="516px" CellPadding="4" ForeColor="#333333" GridLines="None"
Visible="False"
>
<AlternatingRowStyle BorderColor="Black" BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Solicitante/">
<ItemTemplate>
<asp:RadioButton ID="optCl1" runat="server" Text="SI" GroupName="optCl" />
<asp:RadioButton ID="optCl2" runat="server" Text="NO" GroupName="optCl" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CoGarante">
<ItemTemplate >
<asp:RadioButton ID="optGar1" runat="server" Text="SI" GroupName="optGar" />
<asp:RadioButton ID="optGar2" runat="server" Text="NO" GroupName="optGar" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BorderColor="Black" />
<FooterStyle BackColor="#990000" BorderColor="Black" ForeColor="White"
Font-Bold="True" />
<HeaderStyle BackColor="#990000" BorderColor="Black" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#333333" HorizontalAlign="Center" BackColor="#FFCC66" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
The code of the function that read the radiobutton
protected void saveQuestions()
{
foreach (GridViewRow row in GridView8.Rows)
{
RadioButton rb = row.Cells[2].FindControl("optGar2") as RadioButton;
Response.Write(rb.Checked);
}
conn.Close();
}
The code of the function that set the data on the gridview:
protected void loadQuestions()
{
OdbcConnection conn = connection();
conn.Open();
OdbcCommand findSql = new OdbcCommand("SELECT question AS PREGUNTAS,id FROM questionary_reg WHERE(status='1')", conn);
GridView8.DataSource = null;
DataTable dt = new DataTable();
dt.Load(findSql.ExecuteReader());
GridView8.DataSource = dt;
GridView8.DataBind();
conn.Close();
}
The problem because happen postback and reset the values inside the gridview, make sure you
call this function loadQuestions() on if !Postback ONLY
if(!IsPostBack){
loadQuestions();
}
#UPDATE 1 WORKING CODE :
//Design
<asp:GridView runat="server" ID="gv">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" ID="rd" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btn" onclick="btn_Click" />
//Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ToString()))
{
try
{
String cmdText = "SELECT * FROM Image WHERE IsDeleted=#isDeleted";
SqlCommand cmd = new SqlCommand(cmdText, cn);
cmd.Parameters.AddWithValue("#IsDeleted", "false");
cn.Open();
SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
DataTable dt_Category = new DataTable();
myAdapter.Fill(dt_Category);
cn.Close();
gv.DataSource = dt_Category;
gv.DataBind();
}
catch (Exception ex)
{
}
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
RadioButton rd = (RadioButton)gvr.FindControl("rd");
if (rd.Checked)
{
}
else
{
}
}
}
Maybe you need a 'CheckedChanged' event: (Tested and working)
In ASPX set (in this example, you can to see label display the number of row selected)
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbtnSelect" AutoPostBack="true" runat="server" OnCheckedChanged="rbtnSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
and code-behing set
protected void rbtnSelect_CheckedChanged(object sender, EventArgs e)
{
RadioButton selectButton = (RadioButton)sender;
GridViewRow row = (GridViewRow)selectButton.Parent.Parent;
int a = row.RowIndex;
foreach (GridViewRow rw in gvCursos.Rows)
{
if (selectButton.Checked)
{
if (rw.RowIndex != a)
{
lbResultado.Text = rw.RowIndex.ToString();
RadioButton rd = rw.FindControl("rbtnSelect") as RadioButton;
rd.Checked = false;
}
}
}
}
Change this:
RadioButton rb = row.Cells[2].FindControl("optGar2") as RadioButton;
To this:
RadioButton rb = row.FindControl("optGar2") as RadioButton;
for (int i = 0; i < GridView8.Rows.Count; i++)
{
if (GridView8.Rows[i].RowType == DataControlRowType.DataRow)
{
RadioButton rb= (RadioButton)grdView.Rows[i].FindControl("optGar2");
Response.Write(rb.Checked);
}
}
foreach (GridViewRow gvp in gridView1.Rows)
{
System.Web.UI.HtmlControls.HtmlInputRadioButton rd = (System.Web.UI.HtmlControls.HtmlInputRadioButton)gvp.FindControl("rd");
if (rd.Checked)
{
string s = rd.Value;
}
else
{
}
}
design view
<ItemTemplate>
<input runat="server" id='rd' type="radio" value='<%# Eval("id") %>' onclick="javascript:SelectSingleRadiobutton(this.id)" />
</ItemTemplate>

Gridview in Modal Popup Extender- Postback Issues?

I have a C# .Net application with a gridview within an Ajax Modal Popup (VS2008). I have the grid view set to return 10 records per page with paging enabled.
When the user clicks to change page within the gridview there is a postback which closes the modal window and then opens it again using ModalPopup.show();
Is there any way to avoid the postback of the whole page and just postback the gridview whilst keeping the modal window active? At the moment the postback of the whole page gives the impression of flicker...
<asp:Panel ID="Panel1" runat="server" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged"
SelectedIndex="0" ShowHeader="False" Width="700px" ControlID="GridView1"
EventName="PageIndexChanging" Font-Italic="True" Font-Names="Times New Roman"
Font-Size="Medium">
<PagerSettings PageButtonCount="12" />
<RowStyle CssClass="RowStyle" BackColor="#EFF3FB" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE" />
<Columns>
<asp:BoundField DataField="Address" ReadOnly="True">
<ItemStyle Width="385px" />
</asp:BoundField>
<asp:BoundField DataField="XCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
<asp:BoundField DataField="YCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
</Columns>
<FooterStyle CssClass="FooterStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<HeaderStyle CssClass="HeaderStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<EditRowStyle BackColor="#2461BF" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Medium" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="dummy"
BackgroundCssClass="ModalBackgroundGrid" BehaviorID="ModalGrid">
</ajax:ModalPopupExtender>
And the code behind...
public void Page_Load(object sender, EventArgs e)
{
try
{
if (!(Page.IsPostBack))
{
GridView1.EnableViewState = true;
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
GridView1.PagerSettings.Mode = PagerButtons.Numeric;
GridView1.Visible = true;
}
if (!m_bDisclaimerShown)
{
m_bDisclaimerShown = true;
mpe1.Show();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
}
protected void btnHide_Click(object sender, EventArgs e)
{
mpe1.Hide();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
protected void cmdZoomAddress_Click(object sender, EventArgs e)
{
try
{
if (txtPostCode.Text.Length >= 7 && OpenDB())
{
string strPostcode = txtPostCode.Text;
strPostcode = strPostcode.Substring(0, 4) + strPostcode.Substring(strPostcode.Length - 3, 3);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = m_sqlConn;
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.CommandText = "sde.dbo.sp_selAddressByPostcode";
sqlCmd.Parameters.Add("#Postcode", SqlDbType.VarChar);
sqlCmd.Parameters["#Postcode"].Value = strPostcode;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
m_sqlDataTable = new DataTable();
sqlAdapter.Fill(m_sqlDataTable);
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
GridView1.Visible = true;
ModalPopupExtender1.Show();
}
else
{
ShowMsg("Error - No Postal Addresses Returned");
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
finally
{
CloseDB();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (sender != null)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
ModalPopupExtender1.Show();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GVRow = GridView1.SelectedRow;
int iX = (int)Convert.ToSingle(GVRow.Cells[1].Text);
int iY = (int)Convert.ToSingle(GVRow.Cells[2].Text);
GridView1.Visible = false;
MoveMap(iX, iY);
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex >= 0)
{
e.Row.Attributes["style"] = "cursor:pointer";
e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()));
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" + r.RowIndex);
}
}
base.Render(writer);
}
thanks for your suggestion. I've put the gridview into a...
<asp:UpdatePanel>
<ContentTemplate>
The modal now stays however when I click a record in the grid view it doesn't close!

Categories