Need current file download option from the Gridview when file is uploaded - c#

I have a gridview where i upload file and save it to the server. There is something extra in it, like if the wrong file is uploaded we can again upload the same file and its updated version is been reflected on the gridview. Here is my code:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
if (fupreportfile.HasFiles)
{
int count = CheckFileExists(fupreportfile.PostedFile.FileName);
fupreportfile.SaveAs(Server.MapPath("~/ReportFolder/" + fupreportfile.PostedFile.FileName));
if (count > 0)
{
cmd.CommandText = " Update tbl_reports SET revision=#revision Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", GetIdByFileName(fupreportfile.PostedFile.FileName));
cmd.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports updated sucessfully');window.location ='csrreports.aspx';", true);
}
else
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_reports (NgoId,report_type_id,report_title,report_file,report_desc,revision) values(#NgoId, #report_type_id, #report_title,#report_file,#report_desc,#revision)", conn);
cmd1.Parameters.Add("#NgoId", SqlDbType.Int).Value = ddlNgoName.SelectedValue;
cmd1.Parameters.Add("#report_type_id", SqlDbType.Int).Value = ddlReportType.SelectedValue;
cmd1.Parameters.Add("#report_title", SqlDbType.NVarChar).Value = txtreporttitle.Text;
cmd1.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fupreportfile.PostedFile.FileName;
cmd1.Parameters.Add("#report_desc", SqlDbType.NVarChar).Value = txtreportdescription.Text;
cmd1.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports added sucessfully');window.location ='csrreports.aspx';", true);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
For Checking if same file exits or not
public int CheckFileExists(string fileName)
{
try
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tbl_reports WHERE report_file=#report_file", con);
cmd.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fileName;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now what I want is,
What to do in this scenario if I want to download the current file from the gridview.
Please suggest.
UPDATED GRIDVIEW CODE:-
<asp:GridView ID="grdReports"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
OnPreRender="PreRenderGrid"
AutoGenerateColumns="False"
AllowPaging="true"
CssClass="hoverTable"
DataKeyNames="Id"
EmptyDataText="No Records Found!"
HeaderStyle-CssClass="k-grid td"
OnRowCommand="grdReports_RowCommand"
OnDataBound="grdReports_DataBound"
PageSize="10"
ShowFooter="false"
OnPageIndexChanging="grdReports_PageIndexChanging"
OnRowDeleting="grdReports_RowDeleting">
<AlternatingRowStyle CssClass="k-alt" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="5">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" onClick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="title" HeaderText="Report Type" ItemStyle-Width="30" />--%>
<asp:BoundField DataField="report_title" HeaderText="Report Title" ItemStyle-Width="30" />
<asp:BoundField DataField="report_file" HeaderText="Report File" ItemStyle-Width="30" />
<asp:BoundField DataField="report_desc" HeaderText="Report Description" HtmlEncode="false" ItemStyle-Width="30" />
<asp:BoundField DataField="revision" HeaderText="Report Revision" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>

Follow the steps here
Add the TemplateField at the end as below.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("report_file") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2) C# code:-
protected void DownloadFile(object sender, EventArgs e)
{
try
{
string filePath = (sender as LinkButton).CommandArgument;
System.Net.WebClient req = new System.Net.WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath("~/ReportFolder/" + filePath) + "\"");
byte[] data = req.DownloadData(Server.MapPath("~/ReportFolder/" + filePath));
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
throw ex;
}
}

Related

How to download a file from a specific row in GridView

I need some assistance with downloading a file in a specific row in my GridView.
This is my code for the the GridView markup:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="id"
CssClass="mydatagrid"
Width="550px"
BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None"
BorderWidth="1px"
CellPadding="3"
CellSpacing="2"
AllowSorting="true">
<Columns>
<asp:BoundField DataField="filename" HeaderText="Name" />
<asp:BoundField DataField="datestamp" HeaderText="Date" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
Text="Download"
ControlStyle-CssClass="btn btn-success"
CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" width="250px" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
And then for downloading the file I have:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["filecontent"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
So what happens now is when I click on the download it always download the first row's file instead of the row I clicked on to download.
I know I need to specify on which row I have clicked in order to download the file, but not sure on how to accomplish it?
Thanks
It is because of this line
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You then need to change from onclick to a grid command:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server"Text="Download"
ControlStyle-CssClass="btn btn-success" CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
</ItemTemplate>
</asp:TemplateField>
And in your code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["id"];
// you can run your query here
}
}
In your case:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
var val = this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = val;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
You need to also add the onrowcommand="ContactsGridView_RowCommand" to your Gridview
<asp:GridView ID="GridView1" runat="server" onrowcommand="ContactsGridView_RowCommand"

I need my code to Add and bind data to the gridview in asp web form

I don't know what's wrong with the code i've tried to search for possible reasons but haven't figured out yet what's the problem actually.Now the issue is that my web form contains a gridview in which i've place a footer row which will allow the user to add the data and that data gets added to the database and gets binded to the gridview after clicking on the insert link button,But the problem comes when i fill the data and when press link button insert it adds the data twice in gridview and in database too everytime.Below is my whole code which is performing CRUD operation on gridview:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkBtnInsert" runat="server"
CommandName="Insert">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlactive" runat="server">
<asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm2 : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Delete from PersonalDetail" +
" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue(
"#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue(
"#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue(
"#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
}
}
Please try below code :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView1.RowCommand -= GridView1_RowCommand;
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}

SQL Server 2008 filestream read into web page

I have a SQL Server table with filestream enabled. I am able to upload files here and update as well. How do I read these files into an .aspx web page? The files are .pdf files.
There are 2 files are associated with each row.
I am reading the row into a .aspx page and at the bottom I want the files to open up one below the other. This is for the user to print the row with the files.
I have checked out the code suggested by #dinglemeyer. I do want to conver my pdf to image. I am assuming there is a simple way:
<asp:GridView ID="gridview_f" runat="server" ShowHeaderWhenEmpty="false" PageSize="2" DataKeyNames="ID" DataSourceID="sql_files" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="selID" runat="server" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="selFname" runat="server" Text='<%# Bind("filename") %>' />
<br />
<asp:image ID="selFile" runat="server" ImageUrl='<%# "Handler.ashx?id="+Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// code behind for ginfing the grid as the parentId is extracted from other form values.
private void gridView_Data(string id)
{
sql_files.SelectCommand = "SELECT ID, filename from myFILESTABLE where PARENTID=" + id;
}
// Handler.ascx
public void ProcessRequest(HttpContext context)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["my_dbconn"].ConnectionString);
try
{
cmd = new SqlCommand("SELECT filecontent from myFILESTABLE WHERE ID=" + context.Request.QueryString["ID"], conn);
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
context.Response.ContentType = "content/pdf";
context.Response.BinaryWrite((byte[])sdr["filecontent"]);
}
sdr.Close();
}
finally
{
conn.Close();
}
My apologies for the delayed reply.From the link:http://weblogs.asp.net/aghausman/saving-and-retrieving-file-using-filestream-sql-server-2008 Here is my working code:
<asp:GridView ID="mygrid1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" DataSourceID="sql_file" OnRowCommand="gridview_f_RowCommand" GridLines="None" >
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%# Container.DataItemIndex + 1 %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachments" >
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("ID") %>' Visible="false" />
<asp:LinkButton ID="lLabel12" runat="server" Text='<%# Bind("myFileName") %>' CommandName="GetFile" CommandArgument='<%#Eval("ID") + "|" + Eval("myFileName") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
" >
The code behind:
protected void gridview_f_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="GetFile")
{
string[] ca = e.CommandArgument.ToString().Split('|');
SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString);
objSqlCon.Open();
SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
SqlCommand objSqlCmd = new SqlCommand("spGet_getMyFile", objSqlCon, objSqlTran);
objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter objSqlParam1 = new SqlParameter("#ID", SqlDbType.VarChar);
objSqlParam1.Value = ca[0]; // e.CommandArgument;
objSqlCmd.Parameters.Add(objSqlParam1);
string path = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
path = sdr[0].ToString();
}
}
objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
byte[] buffer = new byte[(int)objSqlFileStream.Length];
objSqlFileStream.Read(buffer, 0, buffer.Length);
objSqlFileStream.Close();
objSqlTran.Commit();
Response.AddHeader("Content-disposition", "attachment; filename=" + ca[1]);
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
The Stored procedure SpGet_getMyfile is:
CREATE PROCEDURE [dbo].[spGet_getMyFile]
(
#id BIGINT
)
AS
SELECT filestreamColumn.PathName()
FROM dbo.TableThatHasTheFileStream
WHERE Id=#id

On deleting the Row of GridView not working properly

Whenever I delete a row from the gridview which I select to delete, the row above to the selected row gets deleted. Dont know why. Please see my code for deleting.
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="10" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound" OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Code behind for your ref:-
protected void grdPostData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Post WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrposts.aspx';", true);
grdPostData.DataBind();
}
else
{
Response.Write("Some error");
}
}
Please let me know where I am going wrong. I tried debugging the code and the Id was taking 0.
Gridview bindinf Code:-
public void BindGrid()
{
string strQuery = "Select Id, title, description, Active from tbl_Post Order by ID desc";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
grdPostData.DataSource = dt;
grdPostData.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
try
{
conn.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
sda.Dispose();
conn.Dispose();
}
}
Updated Solution. Completely Working. I am Creating those textboxes in DataBound and theirs a if condition that checks whether Gridview is Empty or Not.
If Gridview is empty then HeaderRow wont be created so that Gridview and Page is able to display else HeaderRow will be Displayed.
Hope this Works for You.
aspx:-
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true"
CodeFile="csrposts.aspx.cs" Inherits="CSRProject.csrposts" %>
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;"
CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="4" CssClass="hoverTable"
OnPageIndexChanging="grdPostData_PageIndexChanging" OnDataBound="grdPostPageData_DataBound"
OnRowDataBound="grdPostData_RowDataBound" DataKeyNames="Id" OnRowDeleting="grdPostData_RowDeleting"
OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30"
ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="lbltbDelete" runat="server" OnClick="lbltbDelete_Click" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this record?')"
CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" CommandName="Delete" ImageUrl="~/images/delete.png"
runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png"
ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png"
UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
No Result Found
</EmptyDataTemplate>
</asp:GridView>
Aspx.cs
protected void grdPostPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
if (grdPostData.Rows.Count > 0)
{
grdPostData.HeaderRow.Parent.Controls.AddAt(0, row);
}
else
{
}
}
protected void grdPostData_RowDataBound(object sender, GridViewRowEventArgs e)
{
/*
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdPostData.HeaderRow.Parent.Controls.AddAt(-1, row);
// e.Row.Parent.Controls.AddAt(1, row);
}
*/
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from tbl_PostCategory ", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList DropDownList1 =
(DropDownList)e.Row.FindControl("ddlPostCategory");
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "cat_title";
DropDownList1.DataValueField = "cat_title";
DropDownList1.DataBind();
}
}
}
Row Deleting Code is Same.
Your code looks good. Hope its not a problem from database. Try this
Add this to Gridview
OnRowCommand="GridView_RowCommand"
CodeBehing:-
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Delete")
{
// Get the value of command argument
int Id= convert.ToInt32(e.CommandArgument);
// Do whatever operation you want.
}
}
Alternatively:-
Add onclick event on your imagebutton of delete and try this
protected void ImageButton_Click(object sender, EventArgs e)
{
ImageButton btn = sender as ImageButton;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int id =Convert.ToInt32((gRow.FindControl("lblId") as Label).Text);
}
Update:-
Change your itemtemplate to this
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' </asp:Label>
</ItemTemplate>
</asp:TemplateField>
So Fetched Id will be visible next to dropdownlist. Make sure its displaying correct value

Approve / reject through dropdownlist

Previously I tried to approve / reject through button and try to code it..
This is code when I add buttons of approve / reject
protected void GrdFileApprove_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "_Approve")
{
//using (SqlConnection con = DataAccess.GetConnected())
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
Button Prove_Button = (Button)row.FindControl("BtnApprove");
SqlCommand cmd = new SqlCommand("approveee", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
//con.Execute("approve", new { UserID, DocID, ApproveID });
cmd.Parameters.Add(new SqlParameter("#UserID", UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Not Approve";
}
finally
{
con.Close();
}
}
}
else if (e.CommandName == "_Reject")
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
LinkButton Prove_Button = (LinkButton)row.FindControl("Button1");
SqlCommand cmd = new SqlCommand("sprejectapprove", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserID",UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Rejct";
}
finally
{
con.Close();
}
}
}
}
and this grdiview when I add dropdown..
<asp:GridView ID="GrdFileApprove" runat="server" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AutoGenerateColumns="False"
onrowcommand="GrdFileApprove_RowCommand" OnRowDataBound="OnRowDataBound" >
<Columns>
<asp:TemplateField HeaderText="S no">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
<asp:HiddenField runat="server" ID="HdnFileID" Value='<%# Eval("DocID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocID" HeaderText="DocumentID" />
<asp:BoundField DataField="DocName" HeaderText="DocName" />
<asp:BoundField DataField="Uploadfile" HeaderText="File Name" />
<asp:BoundField DataField="DocType" HeaderText="Document" />
<asp:BoundField DataField="DepType" HeaderText="Department" />
<%-- <asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
--%> <asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="White" ForeColor="#333333" />
<FooterStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Now I want to code of dropdown.. when I click on approve/reject it can be approve/reject
how to code it and how to approve or reject through dropdown..
I have changed markup for DropDownList4:
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown" AutoPostBack="true" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged">
<asp:ListItem Text="Approve" Value="Approve"></asp:ListItem>
<asp:ListItem Text="Reject" Value="Reject"></asp:ListItem>
</asp:DropDownList>
And in the code:
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
if (ddl.SelectedValue == "Approved")
{
//Code to approve
}
else if (ddl.SelectedValue == "Reject")
{
//Code to reject
}
}

Categories

Resources