how to do custom paging with paging template in asp gridview? - c#

so let say i want to create paging like "> 1 2 3 4 5 6 <" and i decided to use paging template in gridview and this is what i do :
aspx file :
<asp:GridView ID="gvDept" runat="server" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
AllowSorting="True" AllowPaging="True" AllowCustomPaging="True"
DataSourceID="DS" DataKeyNames="departementcode" PageSize="3" OnRowCommand="gvDept_RowCommand">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="cbSelectAll" onclick="SelectAll(this)"></asp:CheckBox>
<%-- <asp:CheckBox runat="server" ID="cbAll" OnCheckedChanged="cbAll_CheckedChanged" AutoPostBack="true"></asp:CheckBox>--%>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="cbSelectOne"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField text="Edit" DataNavigateUrlFields="departementcode"
DataNavigateUrlFormatString="ManageDepartement.aspx?flag=edit&departementcode={0}" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
OnClientClick="return confirm ('Are you sure?');" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
<ItemStyle ForeColor="Red" />
</asp:TemplateField>
<asp:BoundField DataField="departementcode" HeaderText="Departement Code" ReadOnly="True" SortExpression="departementcode" />
<asp:BoundField DataField="departementname" HeaderText="Departement Name" SortExpression="departementname" />
<asp:BoundField DataField="createby" HeaderText="Create By" SortExpression="createby" />
<asp:BoundField DataField="createdate" HeaderText="Create Date" SortExpression="createdate" />
<asp:BoundField DataField="updateby" HeaderText="Update By" SortExpression="updateby" />
<asp:BoundField DataField="lastupdate" HeaderText="Last Update" SortExpression="lastupdate" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black"/>
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerSettings Mode="Numeric" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" CssClass="paging"/>
<PagerTemplate>
</PagerTemplate>
<RowStyle BorderColor="White"/>
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
<asp:LinqDataSource ID="DS" runat="server" ContextTypeName="Admin.AirAsiaDCDataContext"
EntityTypeName="" TableName="departements" EnableDelete="True" OnDeleted="DS_Deleted">
</asp:LinqDataSource>
and then i also put this code in C# :
protected void Page_Load(object sender, EventArgs e)
{
AirAsiaDCDataContext dc = new AirAsiaDCDataContext();
int dtcount = dc.departements.Count();
int pgcount = 0;
if (dtcount % 3 > 0)
{
pgcount = (dtcount / 3) + 1;
}
else
{
pgcount = pgcount / 3;
}
Button pagerBTN;
for (int i = 1; i <= pgcount; i++)
{
if(i == 1)
{
pagerBTN = new Button();
pagerBTN.ID = "btNext";
pagerBTN.Text = ">";
pagerBTN.CommandName = "Next";
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
}
pagerBTN = new Button();
pagerBTN.ID = "bt" + i;
pagerBTN.Text = i.ToString();
pagerBTN.CommandName = i.ToString();
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
if (i == pgcount)
{
pagerBTN = new Button();
pagerBTN.ID = "btLast";
pagerBTN.Text = "<";
pagerBTN.CommandName = "Last";
gvDept.BottomPagerRow.Cells[0].Controls.Add(pagerBTN);
}
}
}
protected void gvDept_RowCommand(object sender, GridViewCommandEventArgs e)
{
AirAsiaDCDataContext dc = new AirAsiaDCDataContext();
int datacount = dc.departements.Count();
int pagecount = 0;
int prevIDX = 0;
if (datacount % 3 > 0)
{
pagecount = (datacount / 3) + 1;
}
else
{
pagecount = datacount / 3;
}
if (e.CommandName == "Next")
{
if (gvDept.PageIndex < pagecount - 1)
{
prevIDX = gvDept.PageIndex;
gvDept.PageIndex = gvDept.PageIndex + 1;
if (prevIDX == pagecount - 2)
{
Button btn = (Button)gvDept.BottomPagerRow.Cells[0].FindControl("btNext");
btn.Visible = false;
}
}
}
else if (e.CommandName == "Prev")
{
if (gvDept.PageIndex > 0)
{
prevIDX = gvDept.PageIndex;
gvDept.PageIndex = gvDept.PageIndex - 1;
if (prevIDX == 1)
{
Button btn = (Button)gvDept.BottomPagerRow.Cells[0].FindControl("btPrev");
btn.Visible = false;
}
}
}
else
{
gvDept.PageIndex = Convert.ToInt32(e.CommandName) - 1;
}
}
my code working, but the problem is, if i click one of those paging button, after postback all my paging button which i generated before totally gone, i don't get it what i do wrong here? any correction?

In the grid view use
OnPageIndexChanging="gvDept_PageIndexChanging"
Add this code in .cs file to bind the data to grid view on each page index change.
protected void gvDept_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDept.PageIndex = e.NewPageIndex;
// write here function to bind the grid to the datasource
}
Add this at the starting in Page_Load function so that the data gets bind to the grid view each time after postback.
if (!IsPostBack)
{
//function to bind the grid to data source
}

Related

I am trying to export grid data into CSV but Audiofilename column data is not displaying

I am trying to export Grid data to csv file in asp.net i exported successfully but Audio File name column data is not displaying in downloaded file (it is button in TemplateField tag i need to print button text in csv file ) ,anything i forget to add ? How to fix this issue ? Thank you
.aspx code
<asp:GridView ID="GridView1" Font-Size="Medium" CssClass="mGrid" runat="server"
HeaderStyle-CssClass="header-center" PageSize="15"
AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<%--<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-ForeColor="White" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("Id")%>' CommandArgument='<%#Eval("Id")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Vendor Name" />
<asp:BoundField DataField="AudFileSize" HeaderText="AudFileSize" />
<asp:BoundField DataField="AudFileDuration" HeaderText="AudFileDuration" />
<%-- <asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
<%-- </ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="FirstName" HeaderText="Physician Name" />--%>
<%--<asp:BoundField DataField="PhysicianID" HeaderText="PhysicianID" />--%>
<asp:BoundField DataField="MrnNo" HeaderText="MrnNo" NullDisplayText=" " />
<asp:BoundField DataField="PatientName" HeaderText="PatientName" NullDisplayText=" "/>
<asp:BoundField DataField="PhysicianName" HeaderText="PhysicianName" />
<asp:BoundField DataField="Reject" HeaderText="Reject" Visible="false" />
<%--<asp:BoundField DataField="BucketName" HeaderText="Bucket Name" Visible="false" />--%>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblBucketName" runat="server" Text='<%#Eval("BucketName")%>' CommandArgument='<%#Eval("BucketName")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code here
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
ExportGridToCSV();
}
private void ExportGridToCSV()
{
//To Export all pages
GridView1.AllowPaging = false;
FillData();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Transcribeworkdetails.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
string[] hiddenCols = { "", "Reject" };
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
columnbind.Append(GridView1.Columns[k].HeaderText + ',');
}
columnbind.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
{
columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}

Nested GridViews in ASP.Net using C# problem with change page

I am trying to open my nested gridview for a single Parent Row and gets correctly open with one single record of the child row.
The paging of the rows is provided in the main gridview.
My problem is the page change, when I try change page I have this error :
GridView paging event gvProducts_PageIndexChanging not firing
How to do resolve this ?
My code below.
Thanks in advance for any help.
Code Markup
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="CustomerID" OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
</Columns>
<PagerTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/aspnet/img/bot_back_doppio.gif"
CommandArgument="First" CommandName="Page" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="/aspnet/img/bot_back.gif"
CommandArgument="Prev" CommandName="Page" />
Page
<asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" CssClass="ddl_Class"
OnSelectedIndexChanged="ddlPages_SelectedIndexChanged">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="/aspnet/img/bot_next.gif"
CommandArgument="Next" CommandName="Page" />
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="/aspnet/img/bot_next_doppio.gif"
CommandArgument="Last" CommandName="Page" />
</PagerTemplate>
</asp:GridView>
Code Behind
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerId = gvProducts.DataKeys[e.Row.RowIndex].Value.ToString();
sql = #String.Format(" SELECT ... ");
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(sql);
gvOrders.DataBind();
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = gvProducts.PageCount.ToString();
for (int i = 1; i <= gvProducts.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = gvProducts.PageIndex;
if (gvProducts.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (gvProducts.PageIndex + 1 == gvProducts.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = gvProducts.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
gvProducts.PageIndex = ddlPages.SelectedIndex;
BindData();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = gvProducts.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
gvProducts.PageIndex = 0;
break;
case "Prev":
gvProducts.PageIndex = intCurIndex - 1;
break;
case "Next":
gvProducts.PageIndex = intCurIndex + 1;
break;
case "Last":
gvProducts.PageIndex = gvProducts.PageCount - 1;
break;
}
gvProducts.DataBind();
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}
Please try this :
[Solution] The GridView 'GridView1' fired event PageIndexChanging which wasn't handled
I hope I was helpful.

Gridview becomes out of shape when rebinds

I have binded gridview to database and it loads on TICKER's event. It works good but problem is that when it rebinds then GIRDVIEW's layout and shape becomes improper and disturbed, kinda messed up.
<asp:GridView ID="GridViewSmsComplaints" AllowPaging="True" PageSize="4" runat="server" AutoGenerateColumns="False" CssClass="mGrid" BorderColor="#333333" Width="550px" OnRowDataBound="GridViewSmsComplaints_RowDataBound" OnPageIndexChanging="GridViewSmsComplaints_PageIndexChanging" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Recieving Date" DataField="RecievingDate" />
<%--<asp:BoundField HeaderText="ToMobileNo" DataField="ToMobileNo" /> --%>
<asp:BoundField HeaderText="FromMobileNo" DataField="FromMobileNo" />
<asp:BoundField HeaderText="Message" DataField="Message" >
<ItemStyle Wrap="True" />
</asp:BoundField>
<asp:TemplateField HeaderText="IsComplaint">
<ItemTemplate>
<asp:CheckBox ID="ckboxIsComplaint" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Timer runat="server" Interval="20000" ID="RefreshSmsComplaints" OnTick="RefreshSmsComplaints_Tick" />
</ContentTemplate>
</asp:UpdatePanel>
Ticker:
protected void RefreshSmsComplaints_Tick(object sender, EventArgs e)
{
// ReportViewer1.Visible = false;
foreach (GridViewRow row in GridViewSmsComplaints.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("ckboxIsComplaint");
if (checkbox.Checked == true)
{
CheckedRows.Add(row.RowIndex);
}
else
{
CheckedRows.Remove(row.RowIndex);
}
}
try
{
DateTime fromDate = DateTime.ParseExact(txtFromDate.Text, "dd/MMM/yyyy", null);
DateTime toDate = DateTime.ParseExact(txtToDate.Text, "dd/MMM/yyyy", null);
DataTable dt = ManageRecievedMessage.GetSmsComplaintsByDate(fromDate, toDate);
//GridViewSmsComplaints.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
if (dt.Rows.Count > 0)
{
GridViewSmsComplaints.DataSource = dt;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = true;
//gridViewComplaintsBySubject.Visible = false;
}
else
{
dt.Rows.Add(dt.NewRow());
GridViewSmsComplaints.DataSource = dt;
GridViewSmsComplaints.DataBind();
int totalcolums = GridViewSmsComplaints.Rows[0].Cells.Count;
GridViewSmsComplaints.Rows[0].Cells.Clear();
GridViewSmsComplaints.Rows[0].Cells.Add(new TableCell());
GridViewSmsComplaints.Rows[0].Cells[0].ColumnSpan = totalcolums;
GridViewSmsComplaints.Rows[0].Cells[0].Text = "No Data Found for this date combination";
GridViewSmsComplaints.Visible = true;
//gridViewComplaintsBySubject.Visible = false;
}
}
catch
{
HiddenFieldSetMessage.Value = "SomethingWrong";
HiddenFieldShowMessage.Value = "True";
}
}

row updating in gridview not working

Gridview update is not happening after I edit it. Used breakpoints and checked, its showing the same existing values which is there before editing. I am not getting any kind of error. Have used Store Procedure to update the Gridview. Please go through the code and help me sort out this problem.
aspx code
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False"
OnRowEditing="gvData_RowEditing"
OnRowDataBound="gvData_RowCreated"
OnRowCreated="gvData_RowCreated"
OnRowCancelingEdit="gvData_RowCancelingEdit"
OnRowUpdating="gvData_RowUpdating"
Style="text-align: center; margin-left: 0px;" Height="160px"
Width="657px" BackColor="#DEBA84" BorderColor="#DEBA84"
orderStyle="None" BorderWidth="0px" CellPadding="3" CellSpacing="2"
DataKeyNames="BtnID" Font-Names="Calibri" ForeColor="#CC3300"
EmptyDataText="No Records Found!!!"
CaptionAlign="Left" HorizontalAlign="Left"
>
<AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" BorderStyle="None" />
<Columns>
<asp:TemplateField HeaderText="BtnID" >
<ItemTemplate>
<asp:Label ID="lblBtnID" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("BtnID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LogdInUsername" >
<ItemTemplate>
<asp:Label ID="lblLogdInUsername" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("LogdInUsername") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:Label ID="lblYear" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Text='<%# Eval("Year") %>' Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Month">
<ItemTemplate>
<asp:Label ID="lblMonth" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Text='<%# Eval("Month") %>' Height="24px" Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server"
ForeColor="#003366" Font-Names="Calibri" Text='<%# Eval("Comments") %>' Font-Size="Small" Height="24px"
Width="20px" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtComments" runat="server"
Width="300px" Text='<%# Bind("Comments") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False"
BorderStyle="None" />
<EmptyDataRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<SortedAscendingCellStyle BackColor="#FFF1D4" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
cs code
protected void Page_Load(object sender, EventArgs e)
{
DTO objc = new DTO();
string str = Environment.UserName;
GrdGetComments();
if (!IsPostBack)
{
GetYear();
GetMonth();
GrdGetComments();
UserPrincipal up1 = GetUserPrincipal(str);
Session["Username"] = str;
Session["Name"] = up1.Name;
LblName.Text = Session["Username"].ToString();
objc.Name = LblName.Text;
LblLogdInUsername.Text = Session["Name"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
LblDateTime.Text = DateTime.Now.ToString();
LblCompany.Text = "";
objc.Company = LblCompany.Text;
}
}
public static UserPrincipal GetUserPrincipal(String userName)
{
UserPrincipal up = null;
PrincipalContext context = new PrincipalContext(ContextType.Domain);
up = UserPrincipal.FindByIdentity(context, userName);
if (up == null)
{
context = new PrincipalContext(ContextType.Machine);
up = UserPrincipal.FindByIdentity(context, userName);
}
if (up == null)
throw new Exception("Unable to get user from Domain or Machine context.");
return up;
}
protected void GetYear()
{
DTO objc = new DTO();
{
DrpForYear.DataSource = obj.GetYear();
DrpForYear.DataTextField = "Year";
DrpForYear.DataBind();
}
}
protected void GetMonth()
{
DTO objc = new DTO();
{
DrpForMonth.DataSource = obj.GetMonth(); ;
DrpForMonth.DataTextField = "Month";
DrpForMonth.DataBind();
}
}
public void GrdGetComments()
{
DTO objc = new DTO();
{
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
DTO objc = new DTO();
int Flag = 0;
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.DateTime = DateTime.Now;
objc.Comments = TxtComments.Text;
objc.Company = LblCompany.Text;
LblName.Text = Session["Name"].ToString();
objc.Name = LblName.Text;
objc.Year = DrpForYear.SelectedItem.Text;
objc.Month = DrpForMonth.SelectedItem.Text;
objc.ViewPreference = RadView.SelectedItem.Text;
int X = obj.InsertButtonComment(objc);
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Comment Saved";
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Save Comment!!!";
}
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
TxtComments.Text = "";
DrpForYear.ClearSelection();
DrpForMonth.ClearSelection();
RadView.Text = "";
}
protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
gvData.EditIndex = e.NewEditIndex;
GrdGetComments();
}
protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvData.EditIndex = -1;
GrdGetComments();
}
protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DTO objc = new DTO();
Label lblBtnID = (Label)gvData.Rows[e.RowIndex].FindControl("lblBtnID");
Label lblLogdInUsername = (Label)gvData.Rows[e.RowIndex].FindControl("lblLogdInUsername");
Label lblYear = (Label)gvData.Rows[e.RowIndex].FindControl("lblYear");
Label lblMonth = (Label)gvData.Rows[e.RowIndex].FindControl("lblMonth");
Label lblComments = (Label)gvData.Rows[e.RowIndex].FindControl("lblComments");
TextBox txtComments = (TextBox)gvData.Rows[e.RowIndex].FindControl("TxtComments");
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.Comments = TxtComments.Text;
objc.BtnID = Convert.ToInt32(Session["BtnID"]);
int Flag = 0;
int X = obj.UpdategvData(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccss.Visible = true;
LblSuccss.Text = "Comment Updated";
}
else
{
LblErrr.Visible = true;
LblErrr.Text = "Failed To Update Comment!!!";
}
}
public int UpdategvData(InLogDTO b)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#LogdInUsername", b.LogdInUsername);
objParam.Direction = ParameterDirection.Input;
objParam.Size = 50;
db.Parameters.Add(new SqlParameter("#Comments", b.Comments));
db.Parameters.Add(new SqlParameter("#BtnID", b.BtnID));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("UpdategvData");
if (retval >= 1)
{
int i = 0;
return i;
}
else
{
return -1;
}
}
stored procedure
ALTER PROCEDURE [dbo].[UpdategvData]
#LogdInUsername nvarchar(50) ,
#Comments nvarchar(50),
#BtnID int
AS
Update dbo.Button_Comments
Set Comments = #Comments
Where LogdInUsername = #LogdInUsername and ViewPreference = 'Public' and
Comments = #Comments and BtnID = #BtnID;
GrdGetComments(); is running in your Page_Load, which binds the gridview again after editing (without saving). This needs to be in the (!IsPostBack).
Page life cycle indicates that Page_Load will always run before any other button clicks:
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx
You need to bind your gridview inside the if (!IsPostBack).
The stored procedure also needs a return value, for example adding a return to the end will allow you to grab this within your C# code.

How can i delete selected data from grid on the button click event?

I have a grid on my page and using check box for checking one or more than one row in grid and i want to delete checked row from grid on the click of delete button which is out side the grid..
In table i have only name field there is no field like ID.
How can i delete record.
Thanks in advance..
Here is my code What i am doing:-
private void GetData()
{
ArrayList arr;
if (ViewState["TotalRecords"] != null)
{
arr = (ArrayList)ViewState["TotalRecords"];
}
else
{
arr = new ArrayList();
}
for (int i = 0; i < grdlistWord.Rows.Count; i++)
{
CheckBox chk = (CheckBox)grdlistWord.Rows[i].Cells[1].FindControl("chkWord");
if (chk.Checked)
{
if (!arr.Contains(grdlistWord.Rows[i].Cells[1]))
{
arr.Add(grdlistWord.Rows[i].Cells[1]);
}
}
else
{
if (arr.Contains(grdlistWord.Rows[i].Cells[1]))
{
arr.Remove(grdlistWord.Rows[i].Cells[1]);
}
}
}
ViewState["TotalRecords"] = arr;
}
protected void lnkbtnDelete_Click(object sender, EventArgs e)
{
try
{
int count = 0;
ArrayList arr = (ArrayList)ViewState["TotalRecords"];
count = arr.Count;
for (int i = 0; i < grdlistWord.Rows.Count; i++)
{
if (arr.Contains(grdlistWord.Rows[i].Cells[1].Text))
{
Response.Write(grdlistWord.Rows[i].Cells[1].Text.ToString());
DeleteRecord(grdlistWord.Rows[i].Cells[1].Text.ToString());
arr.Remove(grdlistWord.Rows[i].Cells[1].Text);
}
}
ViewState["TotalRecords"] = arr;
GridBind();
}
catch (SqlException ex)
{
ex.ToString();
}
}
private void DeleteRecord(string word)
{
string query = "delete from searchword where word=#word";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#word", word);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
gridview html detail:
<fieldset>
<legend>List</legend>
<asp:GridView ID="grdlistWord" runat="server" DataKeyNames="word" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" OnRowDataBound="grdlistWord_RowDataBound" OnRowDeleting="grdlistWord_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkWord" runat="server" onclick="check_click(this);" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick="checkAll(this);" />
<asp:LinkButton ID="ButtonDelete" runat="server" Text="Delete" OnClick="ButtonDelete_Click"></asp:LinkButton>
</HeaderTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Word" HeaderText="Word" />
<asp:HyperLinkField HeaderText="Edit" Text="edit" DataNavigateUrlFields="Word" DataNavigateUrlFormatString="SearchWord.aspx?words={0}&mode=Edit" />
<asp:CommandField ShowDeleteButton="True" HeaderText="Delete" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EmptyDataTemplate>Records not exist!</EmptyDataTemplate>
</asp:GridView>
<asp:HiddenField ID="hfCount" runat="server" Value = "0" />
</fieldset>
protected void lnkbtnDelete_Click(object sender, EventArgs e)
{
int counter = 0;
List<string> words = new List<string>();
foreach (GridViewRow rowitem in grdlistWord.Rows)
{
if (((CheckBox)rowitem.Cells[0].FindControl("chkWord")).Checked == true)//i consider that the check box is in the first column index ---> 0
{
counter++;
words.Add(rowitem.Cells[1].Text); //i consider that the word is in the second column index ---> 1
}
}
/////////////////////////////////////////////////////////////
if(counter == 0) //no checks
{
//show some message box to clarify that no row has been selected.
}
/////////////////////////////////////////////////////////////
if (counter == 1) //one check
{
DeleteRecord(words[0]);
//Show some message box to clarify that the operation has been executed successfully.
}
/////////////////////////////////////////////////////////////
if (counter > 1) //more than one check
{
for(int i=0; i<words.Count;i++)
{
DeleteRecord(words[i]);
}
//Show some message box to clarify that the operation has been executed successfully.
}
grdlistWord.DataBind();
}
For this purpose you have set a primary key id first in your table, which you are fetching as a source of the Grid.
After binding the grid you should save that id in a hidden field. see the code below:
<asp:GridView ID="gvwID" runat="server" AutoGenerateColumns="False"
DataKeyNames="TableID">
<Columns>
<asp:TemplateField>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("TableID") %>'/>
<asp:TemplateField>
</Columns>
</asp:GridView>
Then in the delete button click event get the selected row ids:
protected void Btn_Click(object sender, EventArgs e)
{
int[] OrderIDList = new int[gvwID.Rows.Count];
int index = 0;
for (int count = 0; count < gvwID.Rows.Count; count++)
{
if (gvwID.Rows[count].FindControl("chkSelect") != null)
{
if (((CheckBox)gvwID.Rows[count].FindControl("chkSelect")).Checked)
{
if (gvwID.Rows[count].FindControl("HiddenField1") != null)
{
string OrderID = ((HiddenField)gvwID.Rows[count].FindControl("HiddenField1")).Value;
OrderIDList[index++] = Convret.ToInt32(OrderID);
}
}
}
}
Then create an appended string from OrderIDList and pass it to the stored procedure. from the stored procedure create an xml using the appended string. Loop through the xml and get each id and perform the deletion.
see the procedure below:
#IDList varchar(MAX)
DECLARE #xmlUserIDs xml
SELECT #xmlUserIDs = CONVERT(xml,'<root><cat>' + REPLACE(#IDList,',','</cat><cat>') + '</cat></root>')// creates xml from appended string
DELETE FROM
[TableName]
WHERE
[TableID] IN (SELECT
[Value] = T.C.value('.','int')
FROM
#xmlUserIDs.nodes('/root/cat') T(C));
Hope this helps you..

Categories

Resources