I have a website where users can upload images (part of some report) and I kinda don't know how to save those images.
I think the best way right now is to download those images into a folder of images.
I never really did something like that and everything I tried isn't working.
Here's my code and markup.
HTML markup: the web
<div class="form-group">
<label asp-for="photoPath" class="control-label"></label>
<input asp-for="photoPath" class="" type="file" onchange="readURL(this);" id="file" accept="image/*" multiple />
<span asp-validation-for="photoPath" class="text-danger"></span>
</div>
<div class="form-group" id="display_image" style="display: none; overflow-y: scroll; height: 400px; width: auto;">
<output id="result" style="overflow-y:scroll; height:400px; width:auto; "></output>
<script>
document.querySelector("#file").addEventListener("change", (e) => {
if (window.File && window.FileReader && window.FileList && window.Blob) {
const files = e.target.files;
const output = document.querySelector("#result");
output.innerHTML = "";
for (let i = 0; i < files.length; i++) {
if (!files[i].type.match("image")) continue;
const picReader = new FileReader();
picReader.addEventListener("load", function (event) {
const picFile = event.target;
console.log(picFile.width)
const div = document.createElement("div");
div.innerHTML = `<img class="form-control" id="thumbnail" src="${picFile.result}" title="${picFile.name}" style="height: 500%;width: 200%;"/>`;
output.appendChild(div);
});
picReader.readAsDataURL(files[i]);
document.getElementById('display_image').setAttribute("style", "display:inline;width:auto");
}
} else {
alert("Your browser does not support File API");
}
});
</script>
C# : model class
public class ReportModel
{
/*
Web stuff
*/
[DisplayName("Add photo")]
public List<string> photoPath { get; set; }
/*
More web stuff
*/
}
Well, we need more details as to how and where you plan to save the files.
Assuming a webforms app?
Then probably better to start using asp.net controls. They work MUCH better with your code behind.
So, say this simple markup:
<div id="MyUpLoadArea" runat="server">
<asp:FileUpload ID="FileUpLoad1" runat="server" onchange="ShowImagePreview(this);"
AllowMultiple="True" accept="image/*" style="float:left" />
<asp:Image ID="ImgPrv" Width="160px" runat="server" style="float:left"/>
<div style="clear:both;height:20px"></div>
<asp:Button ID="cmdUpLoad" runat="server" Text="Up-Load" CssClass="btn" OnClick="cmdUpLoad_Click" />
<script>
function ShowImagePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#<%=ImgPrv.ClientID%>').prop('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</div>
So, when we select say 4 files, it displays the first one, and we have this:
So, in above, we have a standard asp.net button we have to click to up-load the files.
The code for that can say be this:
protected void cmdUpLoad_Click(object sender, EventArgs e)
{
string strSQL = "";
SqlCommand cmdSQL;
foreach (HttpPostedFile OneFile in FileUpLoad1.PostedFiles)
{
string strSaveFile = Server.MapPath("~/UpLoadFiles/");
strSaveFile += OneFile.FileName;
OneFile.SaveAs(strSaveFile);
// now add this row to data base
strSQL = "INSERT INTO MyUpLoadFiles (FileName, Size, UpLoadTime, User_ID, SavePath) " +
"VALUES (#FileName, #Size, #UpLoadTime, #User_ID, #SavePath)";
cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#FileName", SqlDbType.NVarChar).Value = OneFile.FileName;
cmdSQL.Parameters.Add("#Size", SqlDbType.Int).Value = OneFile.ContentLength;
cmdSQL.Parameters.Add("#UpLoadTime", SqlDbType.DateTime).Value = DateTime.Now;
cmdSQL.Parameters.Add("#User_ID", SqlDbType.Int).Value = Session["User_ID"];
cmdSQL.Parameters.Add("#SavePath", SqlDbType.NVarChar).Value = "~/UpLoadFiles/" + OneFile.FileName;
General.MyRstE(cmdSQL);
}
// ALL files saved, display the grid of up-loaded files
strSQL = #"SELECT * FROM MyUpLoadFiles
WHERE User_ID = " + Session["User_ID"].ToString() +
" ORDER BY UpLoadTime DESC ";
cmdSQL = new SqlCommand(strSQL);
DataTable rstFiles = General.MyRstP(cmdSQL);
GridView1.DataSource = rstFiles;
GridView1.DataBind();
MyUpLoadArea.Style.Add("display", "none"); // hide up-load area
MyFileView.Style.Add("display", "normal"); // show file grid
}
so, we send/save all files to the folder MyUpLoadFiles.
We save each file into a database - so we can list them out later, and show ONLY the one users file(s).
So, right below the above div and markup, I have a gridview, like this:
<div id="MyFileView" runat="server">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns = "False" ShowHeaderWhenEmpty="true" CssClass="table"
width="50%" >
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="UpLoadTime" HeaderText="UpLoaded" />
<asp:TemplateField HeaderText="Preview" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" width="120px"
ImageUrl = '<% # Eval("SavePath") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
So, now when I hit up-load button, I get/see this:
We of course need to wire up a event for the download button.
Say, this:
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn"
OnClick="cmdDownLoad_Click" />
And that code could be:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button myBut = sender as Button;
GridViewRow gRow = myBut.NamingContainer as GridViewRow;
string strFileOnly = gRow.Cells[0].Text;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
}
I also have two helper routines MyRstP and MyRstE - they are just some general code routines I have (became VERY tired of typing code over and over to get a simple conneciton string setup, and then execute some code to return a table, or to execute some sql code. So, those two routines were this:
public static DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
public static void MyRstE(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
Not really much important - but the above two routines are handy, and thus I don't type that code over and over for simple and general data operations.
Related
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="      "></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.
So I have the data table filled but the column I need image data in is not working. I can see the table filled and can see it is reading the data, but not as a byte array, nor is it displaying the image.
public void Bindformview()
{
try
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
And I know I need to insert this code, or something like it that pulls the data out of the db "thumbnail varbinary(MAX)" column as a byte stream, to get the byte array for the image to display properly:
DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";
table.Columns.Add(column); //Add the column to the table.
and this:
DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);
But I do not need a new column or a new row as those fields are already there.
So how to I fill column "Thumbnail" in the data table, with byte array data to display and where do I do the insert of said code, before the if statement that loads the dt, in the if statement that binds the dt?
do I do it by stating the column like so:
dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());
and then put this in to fill the formview image1 ID like so?
string strBase64 = Convert.ToBase64String(bytes);
formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;
I am just at a standstill and not sure how to do this.
So to be clear, I already have the DB with the Proper image info, and can display it by <asp:image id=image1...etc />, with other code that retrieves the image outside of the formview using this code,
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetImageByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
}
but it doesn't work in a <asp:FormView...etc/> and I need to be able to have it do so for page formating.
This is why I was going in this direction, of using a Data Table right now. If you have a better solution I am open to trying it, as long as it can be used inside of the <asp:formview /> element. Thank you.
So I figured it out:
I Needed to add an Object o; and this line after the databind o = dt.Rows[0]["RecipeId"];
Like So:
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
and made the call to load the image as so:
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Here is the code below if anyone else needs to do the same thing. I will be putting together a for/while or for/next for going through multiple data base entries to display at the same time instead of one at a time currently in this <asp:forview...></formview> element setup.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;
namespace DB_Test1
{
public partial class Search_Results_1 : System.Web.UI.Page
{
string b;
Object o;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Search"] != null)
{
if (Request.QueryString["Text"] != null)
{
string a = Request.QueryString["Text"];
b = a;
recipeSearch(a);
}
}
}
protected void recipeSearch(string a)
{
//Search the database
con.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
catch (Exception ex)
{
//throw new ApplicationException("operation failed!", ex);
}
con.Close();
FormViewRecipes.Visible = true;
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Image1.Visible = true;
}
protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
string a = b;
FormViewRecipes.PageIndex = e.NewPageIndex;
recipeSearch(a);
}
}
}
And here is the ASPX page code:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<hr />
<div class="row">
<div class="col-md-8">
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
</td>
<td>
<asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
<%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
<ItemTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
<%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>'
AlternateText='<%# Eval("ThumbnailAltTxt") %>'
Height="100px" Width="100px" />--%></td>
</tr>
<tr><td><b>Title:- </b></td><td>
<asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
<tr><td><b>Ingredients:- </b></td><td>
<asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>
<tr><td><b>Directions:- </b></td><td>
<asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
<tr><td><b>Notes:- </b></td><td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>
</table>
</ItemTemplate>
<EmptyDataTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
<tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
</table>
</EmptyDataTemplate>
</asp:FormView>
</td>
</tr>
</table>
</div>
<div class="col-md-4">
<p>Ad Space</p>
<asp:Label ID="lblDataTable" runat="server"></asp:Label>
</div>
</div>
</asp:Content>
Just remember I commented out the <asp:image..../a> element field that is in the <Asp:formview.../> element and reset my page layout to get how I wanted it to look for testing.
I am creating DIVs dynamically which will fetch data from my sql table(from each row) and will show it in DIVs. What problem I am facing is, it only shows the last row of my sql table in a div form
Here is the html
<div ID = "containerDiv" class="container" runat = "server">
<div ID = "columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID = "textDiv" class="text" runat="server">
</div>
</div>
</div>
and here is the cs code
static int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblProducts"))
{
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
columnDiv.ID = "columnDiv" + count;
textDiv.ID = "textDiv" + count;
string name = rdr["prod_name"].ToString();
string price = rdr["prod_price"].ToString();
textDiv.InnerHtml = name + " " + price;
columnDiv.Controls.Add(textDiv);
containerDiv.Controls.Add(columnDiv);
count++;
}
}
}
}
Try using a Repeater, like this (here's the MSDN):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div ID="containerDiv" class="container" runat = "server">
<div ID="columnDiv" class="col-md-3 col-sm-4" runat = "server">
<div ID="textDiv" class="text" runat="server">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And supply a DataSource in the code behind on the server, and add '<%# Eval("ColumnName") %>' expressions in the markup where appropriate.
The standard approach is to use a GridView:
https://msdn.microsoft.com/en-us/library/aa479342.aspx
I have display the data on repeater control with asp.net and c#. it's work properly but at last one more line are getting, which i don't want that.
but i can't understand why that line it getting.
and the line is which i don't want "System.Data.SqlClient.SqlDataAdapter".
and my code is: .aspx
<asp:GridView ID="GridView1" DataKeyNames="id" AutoGenerateColumns="false" CellPadding="5"
runat="server">
<Columns>
<asp:TemplateField HeaderText="Add To Compare">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="companyname" DataField="companyname" />
<%-- <asp:BoundField HeaderText="sectorname" DataField="sectorname" />--%>
<asp:BoundField HeaderText="sectorsubname" DataField="sectorsubname" />
<%--<asp:BoundField HeaderText="Location" DataField="email" />--%>
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true"
OnClick="btnProcess_Click" /><br />
<asp:Repeater ID="Repeater3" runat="server">
<ItemTemplate>
<div class="list-1-item">
<div class="list-1-col">
<h4>
<span><%# Eval("companyname")%></span>
</h4>
</div>
<div class="list-1-col center">
<h3>
<span><%# Eval("fieldname") %></span> <b> :</b>
<span><%# Eval("fielddetails")%></span> <b> </b>
</h3>
</div>
<div class="list-1-col center">
<h3>
<%-- <span><%# Eval("fielddetails")%></span> <b> </b>--%>
</h3>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
and my code is : .aspx.cs
protected void btnProcess_Click(object sender, EventArgs e)
{
SqlDataAdapter da;
DataTable dt = new DataTable();
//dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);
if (chkRow.Checked)
{
string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
con.Open();
//string data = "select fieldname,fielddetails from finalcomparedata where compare_id = " + id.ToString() + " ";
string data = "select cd.companyname as CompanyName,fd.fieldname, fd.fielddetails from finalcomparedata fd inner join comparedata cd on fd.compare_id = cd.id where compare_id = " + id.ToString() + " ";
SqlCommand cmd = new SqlCommand(data, con);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dt.Rows.Add(da);
}
con.Close();
}
}
Repeater3.DataSource = dt;
Repeater3.DataBind();
}
You are adding SqlDataAdapater as a row. Your DataTable is filled already no need to add rows.
Comment out or delete this line:
dt.Rows.Add(da);
Better approach:
Define columns for your dataTable, and add new row int the datatable using SqlDataReader:
protected void btnProcess_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("companymame");
dt.Columns.Add("fieldname");
dt.Columns.Add("fielddetails");
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);
if (chkRow.Checked)
{
string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
con.Open();
string data = "select cd.companyname as CompanyName,fd.fieldname, fd.fielddetails from finalcomparedata fd inner join comparedata cd on fd.compare_id = cd.id where compare_id = #id";
SqlCommand cmd = new SqlCommand(data, con);
cmd.Parameters.AddWithValue("#id", id.ToString());
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr["companyname"] = reader[0].ToString();
dr["fieldname"] = reader[1].ToString();
dr["fielddetails"] = reader[2].ToString();
dt.Rows.Add(dr);
}
}
}
con.Close();
}
}
Repeater3.DataSource = dt;
Repeater3.DataBind();
}
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