Gridview databind based on button click - c#

I have the following in my page.
2 Asp Buttons
1 GridView
1 image button for export to excel
I need to view gridview based on respective buttons. i.e. Each button will have different data to displayed. Also gridview should allow paging as there are many records. Export to excel should also happen when image button is clicked including all pages in gridview. Can any one help in this ?
My code is following
aspx file.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<table id="Table2" width="100%" align="left" runat="server">
<tr>
<td class="auto-style8">
</td>
<td class="auto-style9"></td><td class="auto-style10">
<asp:Button ID="Admin" runat="server" Text="Admin" TOOLTIP="Sign In" TABINDEX="3" BackColor="Gray" BorderColor="Black" BorderStyle="Groove" Font-Bold="True" Font-Names="Arial" Font-Size="Large" ForeColor="White" Height="46px" Width="85px"/>
<asp:Menu ID="Menu1" runat="server" StaticSubMenuIndent="" Font-Bold="True" Font-Size="Large">
<Items>
<asp:MenuItem Text="Home" Value="Home" NavigateUrl="Admin_Main.aspx"></asp:MenuItem>
<asp:MenuItem Text="Add Customer" Value="Add Customer" NavigateUrl="Add_Details.aspx"></asp:MenuItem>
<asp:MenuItem Text="Delete Customer" Value="Delete Customer" NavigateUrl="Delete_Customer.aspx"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:LinkButton ID="logout" runat="server" OnClick="logout_click" Font-Bold="True" Font-Size="Large">Logout</asp:LinkButton>
</td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="UserName" Font-Bold="True"
Font-Size="X-Large"></asp:Label>
<asp:TextBox ID="userName" Name= "userName" runat="server" Font-Bold="True"></asp:TextBox>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="Email Log" OnClick= "Email_Click" Height="35px" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:Button ID="Button1" runat="server" Text="All Log" Height="35px" OnClick= "Log_Click" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:ImageButton ID="btnexport" runat="server" Height="35px" ImageUrl="~/Images/exp-xls.gif" Width="112px" OnClick="btnExport_Click" Visible="false" />
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Content>
aspx.cs file
public partial class Display_Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string user = (string)(Session["user"]);
if (!IsPostBack)
{
if (user == null)
{
Response.Redirect("~/InvalidLogin.aspx");
}
else
{
Admin.Text = user;
Admin.Enabled = false;
}
}
}
protected void Email_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" Select Customer_Name,Time_Send_Clicked,Reminder_Type from Email_Log where Username='{0}'",userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename=ActivityReport_" + userName.Text + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Log_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" SELECT [Activity],[Time],[Ticket_Number] FROM Log where Username='{0}'", userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void logout_click(object sender, EventArgs e)
{
this.Session["user"] = null;
this.Session["group"] = null;
Response.Redirect("~/Default.aspx");
}
}

To add pagging u need to specify AllowPaging="True" this will add pagging but it wont work until u specify this which handle the onclick event when page button is clicked
onpageindexchanging="GridView1_PageIndexChanging"
<asp:GridView ID="GridView1"AutoGenerateColumns="false" DataKeyNames="Identityrowoftable" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging" />
in code behind add this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// you need to rebind gridview here
//just set the source and databind
}
after this the print part
first you need to clear controls so unwanted elements dont come while print.
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
how to use ClearControl when exporting as excel
protected void btnExport_Click(object sender, EventArgs e)
{
// Reference your own GridView here
if (GridView1.Rows.Count > 65535)
{
//DisplayError("Export to Excel is not allowed" +
// "due to excessive number of rows.");
return;
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=nameofexcelfile_" + DateTime.Now+".xls" );
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
GridView1.PagerSettings.Visible = false;
ClearControls(GridView1);
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView1GridView1);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
this will print records without paging buttons

Related

Use Checkbox to Insert or Delete a row in Database

I am trying to update a single record in a DataList. I have chosen the DataList type so that I can have a horizontal row with many records on the same page, can use the page to take attendance from a pre-determined list of people, but I want to update as I go. I will be using volunteers to take attendance and don't want to force the users to click save after they are finished (They may get distracted and forget to do so). So, each check box marks a person present. Or unchecking marks them absent.
Here is my CSHTML page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AttendanceTaking.aspx.cs" Inherits="AtChurch.AttendanceTaking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>.ChkBoxClass input {width:25px; height:25px;}
.auto-style1 {
width: 32px;
}
.auto-style2 {
width: 183px;
}
</style>
<table>
<tr>
<td class="auto-style2"><strong>Take Attendance</strong></td>
<td class="auto-style1">Date:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceDate" runat="server"></asp:Label>
</strong>
</td>
<td>
Attendance Group:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceGroup" runat="server" ></asp:Label>
</strong>
</td>
</tr>
</table>
<p>
<asp:HiddenField ID="HiddenAttendanceDate" runat="server" />
<asp:HiddenField ID="HiddenSoCID" runat="server" />
</p>
<p>
<asp:DataList RepeatDirection="Horizontal" RepeatColumns="6" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Both">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<asp:CheckBox ID="CheckBoxPresent" runat="server" RowNumber='<%# Eval("RowNumber") %>' AttendanceID='<%# Eval("AttendanceID") %>' PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
<asp:Label ID="RowNumber" runat="server" Text='<%# Eval("RowNumber") %>' />
<asp:Label ID="FullName" runat="server" Text='<%# Eval("FullName") %>' />
<asp:Label ID="PeopleID" runat="server" Text='<%# Eval("PeopleID") %>' />
<asp:Label ID="AttendanceID" runat="server" Text='<%# Eval("AttendanceID") %>' ></asp:Label>
<asp:Label ID="AttendLabel" runat="server" Text="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"></asp:Label> <br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<FooterTemplate>
:
</FooterTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AtChurchConString %>" SelectCommand="sp_AttendanceTaking" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ChurchID" DefaultValue="0" Name="ChurchID" PropertyName="Value" />
<asp:ControlParameter ControlID="HiddenSoCID" DefaultValue="0" Name="HiddenSoCID" PropertyName="Value" />
<asp:Parameter DefaultValue="1" Name="Select" Type="Int32" />
<asp:ControlParameter ControlID="HiddenAttendanceDate" DefaultValue="" Name="AttendanceDate" PropertyName="Value" Type="DateTime" />
<%--<asp:ControlParameter ControlID="CheckBoxPresent" DefaultValue="0" Name="CheckBoxPresent" PropertyName="Value" />--%>
<%-- <asp:ControlParameter ControlID="AttendanceID" DefaultValue="0" Name="AttendanceID" PropertyName="Value" />--%>
<%--<asp:ControlParameter ControlID="PeopleID" DefaultValue="0" Name="PeopleID" PropertyName="Value" />--%>
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID="ChurchID" runat="server" />
</p>
<p>
</p>
</asp:Content>
And here is my CS page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.SessionState;
namespace AtChurch
{
public partial class AttendanceTaking : System.Web.UI.Page
{
private static string strcon = WebConfigurationManager.ConnectionStrings["AtChurchConString"].ConnectionString;
// Need these for Security
public string strRole, strChurchID, strAttGroup, strAttDate;
public bool ValidUser { get; private set; }
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
if (itm.ItemType == ListItemType.Item )
{
string strPeopleID = ((Label)itm.FindControl("PeopleID")).Text;
string strAttendanceID = ((Label)itm.FindControl("AttendanceID")).Text;
Response.Write(strPeopleID);
Response.End();
//string strAttID = "";
//strAttID = ((DataBoundLiteralControl)item.Controls[1]).Text;
if (ChkBxPresentState == true)
{
Response.Write("Let's Insert it...");
Response.Write(strPeopleID);
Response.End();
}
else
{
//Response.Write("Let's Remove it...");
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
//cmdDelete.Parameters.Add(new SqlParameter("#HiddenSoCID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
cmdDelete.Parameters.Add(new SqlParameter("#CheckBoxPresent", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
Response.Write(intAttendanceID);
Response.Write("-");
Response.Write(1);
Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#CheckBoxPresent"].Value = 0;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (!IsPostBack)
{
// Get Attendance Group ID from the Attendance page.
//if (Request.QueryString["SoCID"].ToString() != null && Request.QueryString["SoCID"].ToString() != null)
string SoCID = Server.UrlDecode(Request.QueryString["SoCID"]);
string AttendanceDate = Server.UrlDecode(Request.QueryString["AttendanceDate"]);
// Response.Write("ok?"+AttendanceDate);
// Response.End();
if (SoCID != null && AttendanceDate != null)
{
strAttGroup = SoCID;
HiddenSoCID.Value = strAttGroup;
lblAttendanceGroup.Text = strAttGroup;
strAttDate = AttendanceDate;
HiddenAttendanceDate.Value = strAttDate;
lblAttendanceDate.Text = strAttDate;
//strAttDate = Request.QueryString["AttendanceDate"].ToString();
//Response.Write(strAttGroup);
//Response.Write(strAttDate);
//Response.End();
}
else
{
//Response.Write("error");
Response.Redirect("Attendance.aspx");
Response.End();
}
}
// Security Start
if (Session["Role"] is null && Session["ChurchID"] is null)
{
Response.Redirect("Login.aspx");
return;
}
if (Session["Role"] != null && Session["ChurchID"] != null)
{
if (!string.IsNullOrEmpty(Session["Role"].ToString()))
{
strRole = Session["Role"].ToString();
strChurchID = Session["ChurchID"].ToString();
}
}
if (strRole == ("SuperAdmin") || strRole == ("ChurchAdmin"))
{
ValidUser = true;
}
if (ValidUser != true)
{
Response.Redirect("Login.aspx");
}
// Security End
//Populate the ChurchID for Insert
ChurchID.Value = strChurchID;
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button_AttendanceTaker_Command(object sender, CommandEventArgs e)
{
}
}
}
This is just the button code of which I am working with to add or delete using my stored procedure.
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
// I added this to try to compare to to get a specific row for Insert
string BoxIndex = ChkBxPresent.Attributes["RowNumber"];
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
// I added this to try to compare to within the Item List
string ItmIndex = ((Label)itm.FindControl("RowNumber")).Text;
if (itm.ItemType == ListItemType.Item)
{
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ((Label)itm.FindControl("SoCID")).Text;
string strAttendanceDate = ((Label)itm.FindControl("AttendanceDate")).Text;
// Here is what we do if the box is checked...
// I used this to try and compare the values. It showed the one I wanted to
// compare to but the ItmIndex only returned odd rows. So I don't match somtimes
//Response.Write("BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
// I added the compare of ItmIndex == BoxIndex but it was not consistent. Again it was only returning odd
// numbers and no even numbers to compare to for some reason.
if (ChkBxPresentState == true)
{
string strAction = "ADD";
//Response.Write("Add BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
SqlConnection con = new SqlConnection(strcon);
//Response.Write("Let's Insert it...");
//Response.Write("PeopleID");
//Response.Write(strPeopleID);
//Response.Write("ChurchID");
//Response.Write(strChurchID);
//Response.Write("GroupID");
//Response.Write(strAttGroupID);
//Response.Write("AttDate");
//Response.Write(strAttendanceDate);
//Response.Write("Action");
//Response.Write(strAction);
//Response.End();
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
}
else
{
string strAction = "DEL";
//Response.Write("DEL BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
//Response.Write(" |");
// Here is what we do if the Box is unchecked
//Response.Write("Let's Remove it...");
//Response.Write(strPeopleID);
//Response.Write("aID");
//Response.Write(strAttendanceID);
//Response.Write("checkBoxPresent:");
//Response.Write(strCheckBoxPresent);
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
It's obviously not complete as I'm just trying to get it to show the right data. I did a test of the delete portion (When the box is unchecked) and it did not delete a specific record because the EventArgs returns all the checkbox values. If I change it to DataListItemEventArgs it returns specific rows but then I lose the functionality of the checkbox on check. I think I need to separate these but I am not sure how to accomplish this task.
Here is the functionality I am going for:
1. Setup the date and retrieve any attendance if already taken.
Image of form that loads the AttendanceTaker
And a sample of the page I am going for with a large checkbox so it can be used on a tablet.
Sample of AttendanceTaker page
I rewrote the code using the idea from selected answer. This was the code that ended up working.
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
if (Int32.TryParse(ChkBxPresent.Attributes["AttendanceID"].ToString(), out int intAttendanceID)) { }
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ChkBxPresent.Attributes["SoCID"];
string strAttendanceDate = ChkBxPresent.Attributes["AttendanceDate"];
if (intAttendanceID == 0) // Add Attendance Record it does not exist and was checked
{
string strAction = "ADD";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
}
else // Delete Attendance Record it was unchecked
{
string strAction = "DEL";
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
// End delete data
}
////end of checkbox
You can pass the value of the PeopleId (and/or attendanceID) in the checkbox as an attribute and avoid iterating over the DataList.
Your checkbox
<asp:CheckBox ID="CheckBoxPresent" runat="server" PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
Code behind
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
Then if it's checked, issue insert command for that ID only, if it's unchecked, issue delete command for that ID.

C# Identifying the Row in a gridview inorder to Delete

I am working on a project in which I am to display, insert, delete the data in my access database. I made buttons that will display a specific table from the database. I then made an asp column to display the delete button next to each row. The issue that I am trying to figure out is: How can I have it so that when the delete button is clicked the specific row is identified so then I may delete it? Any hints or tips are welcomed. Thank you.
<body>
<h1 class="center" style="text-align: center" >Display, Delete, and Add</h1>
<h3 id="Title1"></h3>
<style>
.center{
margin: 0 auto;
}
</style>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" class="center" runat="server" Width="300px" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
</p>
<p >
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Courses" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Student Information" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Students" />
</p>
<p>
</p>
<p>
</p>
<p>
</p>
</form>
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con = new OleDbConnection (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\achowdhary\Documents\Database1.accdb");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM COURSES", con);
DataSet set = new DataSet();
ada.Fill(set, "COURSES");
DataTable tab = new DataTable();
tab = set.Tables["COURSES"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENT_INFO", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENT_INFO");
DataTable tab = new DataTable();
tab = set.Tables["STUDENT_INFO"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
OleDbDataAdapter ada = new OleDbDataAdapter(" SELECT * FROM STUDENTS", con);
DataSet set = new DataSet();
ada.Fill(set, "STUDENTS");
DataTable tab = new DataTable();
tab = set.Tables["STUDENTS"];
GridView1.DataSource = tab;
GridView1.DataBind();
}
protected void btn1_Click(object sender, EventArgs e)
{
//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "hello" + "');", true);
}
}
Many possibilites, my prefer is, bind a commandArgument in button with your identifier, and recover this value on post back
protected void btn1_Click(object sender, EventArgs e)
{
var identifier = ((Button)sender).CommandArgument;
}
Html
<ItemTemplate>
<asp:Button ID="btn1" Text="Delete" runat="server" OnClick="btn1_Click" CommandArgument='<%# Eval("PropertyName") %>'/>
</ItemTemplate>

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();
}

displaying read more option when user enters large amount of data in richtextbox

I have a richtextbox and a gridview.
When I enter the data into the richtextbox, it should be displayed in a gridview and saved in database.
Now my requirement is that, if i am entering a paragraph or a large amount of data I should display a "readmore" button, that when clicked, display the complete data.
<%# Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" />
<br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
c# code-
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(#Richtextbox)", con);
cmd.Parameters.AddWithValue("#Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
first in your select query add id of your text(your primary key of table RichTextBoxData)
and in gridview make it,s visible =false like this
<asp:TemplateField HeaderText="id" InsertVisible="False" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and then
protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lb =e.Row.FindControl("lbltxt") as Label;
if (lb.Text.Length > 15)//any length u want
{
DataRow drv = ((DataRowView)e.Row.DataItem).Row;
int tempID = Convert.ToInt32(drv["id"].ToString());
HyperLink hp = new HyperLink();
hp.Text = "read more";
hp.NavigateUrl = "~/mydetails.aspx?id=" + tempID;
e.Row.Cells[1].Controls.Add(hp);
lb.Text = lb.Text.Substring(0, 15);
}
}
}
and on page_load of mydetails.aspx make
query to select RichTextData where id=request.querystring["id"]

Change gridview header text when i choose dropdownlist

I have some doubt
This is my coding for aspx page and .cs page
How can I achieve the following
If i select February the header text assigned January value and i select march then assign February value...Could you please help me find a solution for it
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="8-14">
<ItemTemplate>
<asp:TextBox ID="TxtWeek2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .CS page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select");
DropDownList1.Items.Add("January");
DropDownList1.Items.Add("February");
DropDownList1.Items.Add("March");
DropDownList1.Items.Add("April");
DropDownList1.Items.Add("May");
SqlConnection cn = new SqlConnection("Data Source=192.169.10.22;Initial Catalog=SHRICITYUNO;User ID=uno;Password=uno");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd = new SqlCommand("SELECT Week1 FROM Finman_FundPlan", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedItem.Text.ToString();
if (DropDownList1.SelectedItem.Text == "January")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "February")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "-";
}
else if (DropDownList1.SelectedItem.Text == "March")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "April")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-30";
}
else if (DropDownList1.SelectedItem.Text == "May")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
}
you can do it using Javascript at client side.
if you observe the grid view then you can notice that row[0] is the header row for gridview.
now you can check decide the which cell test you have to change.
see the following javascript function to accomplish your task
<script language="Javascript">
function ChangeHeaderText()
{
var gridObject = document.getElementById("Gridview1");
gridObject.rows[0].cells[0].innerText = 'NewHeader Text';
return false;
}
</script>
//call above function on 'onchange' event of dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange = "return ChangeHeaderText()"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Try this It will work......

Categories