View pdf file in another page - c#

Here have code to view pdf file and currently the file can be viewed in the same page.I want to display file in new page when the linkbutton clicked in gridview. As understood that Literal embed link needs to be changed but I am not sure about that. My question is how to view the file in new page?
Gridview code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="comName" HeaderText="Company Name" SortExpression="comName" />
<asp:BoundField DataField="sName" HeaderText="Stock Name" SortExpression="sName" />
<asp:BoundField DataField="annDate" HeaderText="Date Announced" SortExpression="annDate" />
<asp:BoundField DataField="fYearEnd" HeaderText="Financial Year End" SortExpression="fYearEnd" />
<asp:BoundField DataField="quarterr" HeaderText="Quarter" SortExpression="quarterr" />
<asp:BoundField DataField="QFREDate" HeaderText="Financial Period Ended " SortExpression="QFREDate" />
<asp:BoundField DataField="figure" HeaderText="Figure" SortExpression="figure" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("id") %>'></asp:LinkButton>
</ItemTemplate>
code behind for view:
protected void View(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"100%\" height=\"100%\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), id);
}
FileCS.ashx code:
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["Id"]);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT fName, contentType, data FROM announ WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["data"];
contentType = sdr["contentType"].ToString();
fileName = sdr["fName"].ToString();
}
con.Close();
}
}
context.Response.Buffer = true;
context.Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}

in your link button add OnClientClick="aspnetForm.target ='_blank';"
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" OnClientClick="aspnetForm.target ='_blank';" CommandArgument='<%# Eval("id") %>'></asp:LinkButton>
this will open a new tab.

Related

How do I maintain editing a row without scrolling back up when I click on the edit button?

I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?
Default.aspx
<%# Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<br /><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
<br />
</div>
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black" PageSize="15" AllowPaging="True" >
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.cs
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.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
public bool fcEditTBL_USERS
(int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
try
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", DbType.Int32));
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add("#ID", SqlDbType.Int).Value=tbl_users_key ;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value=Name;
sqlCmd.Parameters.Add("#CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
sqlCmd.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value=Employee;
sqlCmd.Parameters.Add("#FootPlate", SqlDbType.Bit).Value=FootPlate;
sqlCmd.Parameters.Add("#WirstCord", SqlDbType.Bit).Value=WirstCord;
sqlCmd.Parameters.Add("#Excluded", SqlDbType.Bit).Value=Excluded;
sqlCmd.Parameters.Add("#Comment", SqlDbType.VarChar, 255).Value=Comment;
sqlCmd.Parameters.Add("#MODE", SqlDbType.SmallInt).Value =iMode;
sqlCmd.Parameters.Add("#MSG", SqlDbType.NVarChar, 255).Value=sMsg;
sqlCmd.Parameters["#MSG"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
sMsg = sqlCmd.Parameters["#MSG"].Value.ToString();
int rtn = (int)sqlCmd.Parameters["#RETURN_VALUE"].Value;
if (rtn != 0)
{
return false;
}
sqlCmd.Dispose();
return true;
}
finally
{
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
gvTestUsers.PageIndex = e.NewPageIndex;
PopulateGridView();
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand (find,con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("LoginForm.aspx");
}
}
}
Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps.
Working below code for me.
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");
//add this
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
And the row deleting below,
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
I solved it by moving the SearchBox-Event code into my PopulateGridView.
So now the PopulateGridView looks like this:
void PopulateGridView()
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
And the Searchbox-Event:
protected void Button1_Click(object sender, EventArgs e)
{
PopulateGridView();
}
Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.

Problem adding in a ASP.NET grid view image from SQL database

I created a grid view that contains a column for images, after I write all necessary code the image is still not showing. Can you look at the code and see if there is something that i'm doing wrong? This is my ASP.NET Grid View:
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Height="229px" Width="404px">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<img id="img1" src='Handler1.ashx.cs?ProductID=<%# Eval("ProductID").ToString() %>' height="70" width="70"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ProductID") %>' OnClick="lnk_OnClick">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my button that when clicked should display the images in the ASP.NET grid view
protected void btnSave_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ProductCreateOrUpdate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#ProductID", (hfProductID.Value == "" ? 0 : Convert.ToInt32(hfProductID.Value)));
sqlCmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Image", FileUpload2.FileBytes);
sqlCmd.Parameters.AddWithValue("#Description", txtDescription.Text.Trim());
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
string productID = hfProductID.Value;
Clear();
if (productID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
FillGridView();
}
And this is the general Handler.ashx
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string Constr = System.Configuration.ConfigurationManager.ConnectionStrings[#"connection String"].ToString();
string pici = context.Request.QueryString["ProductID"];
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(Constr))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT Image FROM Product WHERE ProductID=#ProductID", conn))
{
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("ProductID", pici));
conn.Open();
using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Image")]);
reader.Close();
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

Gridview Footer Not an Instance

I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FRACCIONES">
<EditItemTemplate>
<asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLAVE SAT">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Below is the code sample for binding the grid in code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string query;
string countid = " ";
SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
llenagrid();
IncrementoID();
}
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
IncrementoID();
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Agregar_Click(object sender, ImageClickEventArgs e)
{
connStr.Open();
GridViewRow row = GridView1.FooterRow;
TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
SqlCommand com = new SqlCommand(str,connStr);
int count = Convert.ToInt32(com.ExecuteScalar());
connStr.Close();
if (count > 0)
{
string script = "alert('Este Nombre ya Existe.','AtenciĆ³n');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
}
else
{
connStr.Open();
TextBox txtID = (TextBox)row.FindControl("txtAddID");
CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
TextBox txtClave = (TextBox)row.FindControl("txtClave");
string ID = txtID.Text;
string Nombre = txtNombre.Text;
bool Fracc = chkFracc.Checked;
string clave = txtClave.Text;
string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
SqlCommand cmd2 = new SqlCommand(query2, connStr);
cmd2.ExecuteNonQuery();
connStr.Close();
llenagrid();
IncrementoID();
}
}
public void IncrementoID()
{
//query = "select Count(id_unidad) from unidades";
//con.Open();
//SqlCommand cmd = new SqlCommand(query, con);
//string cid = cmd.ExecuteScalar().ToString();
//con.Close();
//TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
//ID.Text = countid + (int.Parse(cid) + 1);
//ID.ReadOnly = true;
con.Open();
SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
SqlDataReader rd = cmd.ExecuteReader();
TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
if (rd.Read())
{
string Value = rd[0].ToString();
if (Value == "")
{
txtID.Text = "1";
}
else
{
txtID.Text = rd[0].ToString();
txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
}
}
con.Close();
}
}
As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.
Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
//IncrementoID(); // Remove the function call from here
GridView1.DataSource = table;
GridView1.DataBind();
IncrementoID(); // Call the function after GridView got binded.
}

Can a data that show file path downloadable using c#

I am trying to make a page where the page can display a list of data and users can download the data. First, the data is a file name and the file name is like a filepath. For example C/user/file.pdf. Below is my coding:
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Ulysses"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT TOP 10 OLE_LINK_FILE_NAME FROM OLE_LINK";
//cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
fileName = sdr["OLE_LINK_FILE_NAME"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
//Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
Below is my HTML coding:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="OLE_LINK_FILE_NAME" HeaderText="File Name"/>
<asp:TemplateField ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("OLE_LINK_FILE_NAME") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Is it possible to download a data like that or not. If can, the page can display the data but I cannot download the file when I click the download link. Is there anything wrong with my coding? Here is the link of tutorial that I use as a guide: http://www.aspsnippets.com/Articles/Upload-and-Download-files-from-SQL-Server-Database-in-ASPNet.aspx

C# grid view files doesnt open

I am uploading a file to my server and storing its file name and file path in the SQL database.
I am trying to display the file in the gridview... but doesn't open.
Below is my code
<asp:GridView ID="GridView1" runat="server" Width="45%" style="text-align:center;"
AutoGenerateColumns="false" HeaderStyle-ForeColor="White" DataKeyNames="TASK_ID"
AllowPaging ="true" emptydatatext="No Attachments" BackColor="AliceBlue" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F2F2F2" RowStyle-BorderWidth="1" AlternatingRowStyle-BorderWidth="1"
HeaderStyle-BackColor = "#00829c" HeaderStyle-BorderColor="#CC9966" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="TASK_ID" Visible="false" HeaderText="Id" />
<asp:BoundField DataField="ATTACH_FILENAME" HeaderText="FileName" />
<asp:TemplateField HeaderText="View" HeaderStyle-Width="90%">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" Target="_blank" runat="server" Text='<%# Eval("ATTACH_FILENAME") %>'
NavigateUrl='<%# Eval("ATTACH_FILEPATH") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
private void Binddata()
{
string strQuery = "SELECT TASK_ID,ATTACH_FILENAME,ATTACH_FILEPATH from child_taskcreator where TASK_ID ='" + lblTaskid.Text + "'";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = connection;
connection.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
connection.Close();
return dt;
}
Please someone correct me... I wanted the users to open or save the document
// code to upload files
HttpFileCollection fileCollection = Request.Files;
if (fileCollection.Count != 0)
{
string filename = string.Empty;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile file = fileCollection[i];
filename = Path.GetFileName(file.FileName);
if (file.ContentLength > 0)
{
string strFilePath = "~/Uploads/";
System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(MapPath(strFilePath));
if (!DI.Exists)
{
System.IO.Directory.CreateDirectory(MapPath(strFilePath));
}
strFilePath = strFilePath + filename;
System.IO.FileInfo FI = new System.IO.FileInfo(MapPath(strFilePath));
if (!FI.Exists)
{
file.SaveAs(Server.MapPath(strFilePath));
}
// save the filepath variable to your database
}
}
}
Save the filepath variable to your database, then it will get retrieved from your gridview

Categories