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
Related
Morning everyone, I'm a newbie of c#.
The code below
<asp:LinkButton ID="insert_new_user" runat="server" OnClick="insert_new_user_Click"
CommandName="insertnewuser" Text="add new user" BorderColor="#000099">
</asp:LinkButton>
<asp:TemplateField HeaderText="Resign?" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:CheckBox ID="cb_isleave" runat="server" Checked='<%# Eval("BS_LEAVE") %>'
Visible="True" Enabled="False" ForeColor="#ff0000" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="ed_cb_isleave" runat="server" Checked='<%#Eval("BS_LEAVE") %>'
Visible="True" Enabled="true" ForeColor="#ff0000" />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="ft_cb_isleave" runat="server" Checked="false"
Visible="True" Enabled="true" />
</FooterTemplate>
</asp:TemplateField>
When the database is empty I use these code to render a empty footer row and header
protected void insert_new_user_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string fakequery_user = "SELECT TOP 1 [A].[BS_ID],[A].[BS_NAME_CHT],[BS_NAME_ENG] = ISNULL([A].[BS_NAME_ENG], '-'),[BS_LEAVE]=ISNULL([A].[BS_LEAVE],0),[B].[BS_NAME]" +
"FROM[BS_USER][A] LEFT OUTER JOIN[BS_DEPT][B] ON[A].[BS_DEPT] = [B].[BS_ID]";
SqlCommand fakequery = new SqlCommand(fakequery_user, conn);
conn.Open();
SqlDataAdapter da1 = new SqlDataAdapter(fakequery);
SqlDataReader dr = fakequery.ExecuteReader();
if (dr.HasRows)
{
DataTable FinalUserData = this.Bulid_UserTB();
conn.Close();
conn.Open();
da1.Fill(FinalUserData);
DataSet datasetfinaluserdata = new DataSet();
datasetfinaluserdata.Tables.Add(FinalUserData);
conn.Close();
da1.Dispose();
USER_TABLE.DataSource = datasetfinaluserdata;
USER_TABLE.DataBind();
USER_TABLE.Rows[0].Visible = false;
}
else
{
if (USER_TABLE.Rows.Count == 0)
{
renderEmptyGridView(USER_TABLE, "BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_NAME, BS_INSERTOR, BS_INSERT_TIME, BS_EDITOR, BS_EDIT_TIME, BS_LEAVE");
}
}
}
}
public static void renderEmptyGridView(GridView EmptyGridView, string FieldNames)
{
DataTable dTable = new DataTable();
char[] delimiterChars = { ',' };
string[] colName = FieldNames.Split(delimiterChars);
foreach (string myCol in colName)
{
DataColumn dColumn = new DataColumn(myCol.Trim());
dTable.Columns.Add(dColumn);
}
DataRow dRow = dTable.NewRow();
foreach (string myCol in colName)
{
dRow[myCol.Trim()] = DBNull.Value;
}
dTable.Rows.Add(dRow);
EmptyGridView.DataSourceID = null;
EmptyGridView.DataSource = dTable;
EmptyGridView.DataBind();
EmptyGridView.Rows[0].Visible = false;
}
but when I run the web, the error pop up said, "Specified cast is not valid."
I think is it the foreach() is string but in the database the "BS_LEAVE" is a Boolean?
How can I solve it ? Thank You
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.
I tried the sorting functionality like below
<asp:GridView ID="grdUser"
AllowPaging="true"
AutoGenerateColumns="False"
OnDataBound="grdUser_DataBound"
OnRowDeleting="grdUser_RowDeleting"
OnPreRender="PreRenderGrid"
runat="server"
Width="100%"
border="1"
DataKeyNames="Id"
PageSize="10"
EmptyDataText="No Records Found"
OnPageIndexChanging="grdUser_PageIndexChanging"
EnableSortingAndPagingCallbacks="false"
CssClass="hoverTable"
AllowSorting="true"
OnSorting="grdUser_Sorting"
ShowFooter="false"
HeaderStyle-CssClass="k-grid td"
OnRowCommand="grdUser_RowCommand">
<AlternatingRowStyle CssClass="k-alt" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="5">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="username" HeaderText="Username" SortExpression="username" ItemStyle-Width="30" />
<asp:BoundField DataField="email" HeaderText="Email ID" SortExpression="email" ItemStyle-Width="30" />
<asp:BoundField DataField="ngoname" HeaderText="NGO Name" ItemStyle-Width="30" />
<asp:BoundField DataField="usertype" HeaderText="UserType" ItemStyle-Width="30" Visible="false" />
<asp:BoundField DataField="UserRoleName" HeaderText="User Role" ItemStyle-Width="30" />
<asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" ToolTip="Edit" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" ToolTip="Delete" 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>
Also see my code behind:-
protected void grdUser_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["tbl_User"] as DataTable;
DataView dataView = new DataView(dt);
dataView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
grdUser.DataSource = dataView;
grdUser.DataBind();
}
private string GetSortDirection(string column)
{
string sortDirection = "ASC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
But when I debugged the code, I am always getting dt as null.
Please help
UPDATE
Code for binding gridview:-
protected void BindGrid()
{
string username = string.Empty;
string usertype = string.Empty;
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT usertype,username FROM tbl_User WHERE username=#username", conn);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = Session["User"].ToString();
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
username = dr["username"].ToString();
usertype = dr["usertype"].ToString();
}
}
conn.Close();
string query = string.Empty;
if (!string.IsNullOrEmpty(usertype))
{
if (usertype == "0") // superadmin
{
query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,tbl_User.email,tbl_User.usertype,tbl_User.active,(CASE WHEN tbl_User.usertype='1' THEN 'Admin' WHEN tbl_User.usertype='0' THEN 'Super Admin' WHEN tbl_User.usertype='2' THEN 'User' END) AS UserRoleName FROM tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId ORDER By Id DESC";
}
if (usertype == "1") // admin
{
query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,tbl_User.email,tbl_User.usertype,tbl_User.active,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId WHERE usertype != '0' ORDER By Id DESC";
}
if (usertype == "2") // user
{
query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,tbl_User.email,tbl_User.usertype,tbl_User.active,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId WHERE username='" + username + "' ORDER By Id DESC";
}
cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grdUser.DataSource = ds.Tables[0];
grdUser.DataBind();
DisablePageDirections();
grdUser.BottomPagerRow.Visible = true;
Session["tbl_User"] = ds.Tables[0];
}
}
catch (Exception)
{
throw;
}
}
ADDED MORE CODE:-
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
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();
}
}
You are setting session with name tbl_user on page load and when you get it you are getting with GridViewData.
On page load you set session with name tbl_user
Session["tbl_User"] = dt;
And you get it with name GridViewData
DataTable dt = Session["GridViewData"] as DataTable;
When you get the datatable from session in grdUser_Sorting change it like this
protected void grdUser_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["tbl_user"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
grdUser.DataSource = Session["tbl_user"];
grdUser.DataBind();
}
}
I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My 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.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
Following is my code... I am trying to store image in database. I have used varbinary(MAX) datatype for storing data bytes in database. Please tell me where I am going wrong.
int qtype = Convert.ToInt32(ddl_q_Type.SelectedValue);
var getQ = (from q in obj.QuestionRegistrations
orderby q.QueCode ascending
where q.QueQuesType == qtype && q.QueLanguageCode == 1
select new { q.QueCode, q.QueQuestion }
).ToArray();
index = Convert.ToInt32(ViewState["index"].ToString()) + 1;
ViewState["index"] = index;
previosIndex = index - 1;
ViewState["previosIndex"] = previosIndex;
txt_question.Text = getQ[index].QueQuestion;
lblqcode.Text = getQ[index].QueCode.ToString();
int qcode = Convert.ToInt32(lblqcode.Text);
var options = (from opt in obj.QuestionAndOptionsMappings
where opt.QueMapQuestionCode == qcode
select new { opt.QueMapOptions, opt.QueMapCorrectAnswer, opt.QueMapId, opt.QueMapImage }
).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("QueMapOptions", typeof(string));
dt.Columns.Add("QueMapId", typeof(string));
dt.Columns.Add("QueMapImage", typeof(string));
foreach (var y in options)
{
DataRow dr = dt.NewRow();
dr["QueMapOptions"] = y.QueMapOptions;
dr["QueMapId"] = y.QueMapId;
dr["QueMapImage"] = (Byte[])y.QueMapImage;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
This code for storing the image in databse
for (int i = 0; i < GridView1.Rows.Count; i++)
{
FileUpload fp = (FileUpload)GridView1.Rows[i].Cells[2].FindControl("fp");
Label lblmapid = (Label)GridView1.Rows[i].Cells[1].FindControl("lblmapid");
bool e1 = fp.HasFile;
int mapiidd = Convert.ToInt32(lblmapid.Text);
if (fp.HasFile)
{
string path = Server.MapPath("~/Uploads/") + fp.FileName;
fp.SaveAs(path);
byte[] imageBytes =
File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/") + fp.FileName);
int qcodelbl = Convert.ToInt32(lblqcode.Text);
QuestionAndOptionsMapping qmap = new QuestionAndOptionsMapping();
var update = obj.QuestionAndOptionsMappings.Where(q => q.QueMapId == mapiidd && q.QueMapQuestionCode == qcodelbl)
;
update.SingleOrDefault().QueMapImage = imageBytes;
obj.SaveChanges();
}
}
ASPX code
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="OPTIONS" HeaderStyle-Width="55%">
<ItemTemplate>
<asp:TextBox ID="Option" runat="server" Text='<%#Eval("QueMapOptions") %>' Height="40px"
Width="500px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%" Visible="false">
<ItemTemplate>
<asp:Label ID="lblmapid" runat="server" Text='<%#Eval("QueMapId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:CheckBox ID="Chk_correct_Ans" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:FileUpload ID="fp" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("QueMapImage") %>' Height="80px"
Width="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok, you can't just bind a binary column to a GridView column. you need to make use of Response.BinaryWrite method.
Here are few steps to follow to achieve what you want
Create a generic handler to read binary data. We'll call it ImageHandler.ashx. Make sure you have the primary key of the table to be passed to this handler. Write the handler code something like below (just an example).
public void ProcessRequest (HttpContext context)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
And call the handler like this.
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'
instead of
ImageUrl='<%#Eval("QueMapImage") %>'
Here's a complete example from where I extracted above examples.
All the best!