How to insert image from gridview to another table in database - c#

Dear all I am displaying an image in my gridview, this image is saved in database in varbinary format, with its content type and image name. And my image in gridview is displaying perfect, now I want to insert this same image from gridview to another table from the button click outside the gridview, How do I achieve this can anyone please guide me? I tried achieving it by receiving this image data from gridview such as Varbinary data - which is an image in database and content type and imagename into textbox but it thorws an error "Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query"
<asp:TemplateField HeaderText="" ItemStyle-Width="" Visible="true">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" class="preview" ToolTip='<%#Bind("StaffName") %>'
NavigateUrl='' runat="server">
<asp:ImageButton runat="server" ID="Image2" class="img2" ImageUrl='<%# Eval("ImageName") %>'
CommandName='<%# Eval("Id") %>' CommandArgument='<%# Eval("ImageName") %>' />
</asp:HyperLink>
<asp:TextBox ID="txtFileType" runat="server" Text='<%# Eval("FileType") %>' Visible="true"></asp:TextBox>
<asp:TextBox ID="txtBData" runat="server" Text='<%# Eval("BData") %>' Visible="true"></asp:TextBox>
<asp:TextBox ID="txtImageName" runat="server" Text='<%# Eval("ImageName") %>' Visible="true"></asp:TextBox>
<br />
<br />
</ItemTemplate>
<ControlStyle Width="100%" />
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
</asp:TemplateField>
foreach (GridViewRow row1 in gvImage.Rows)
{
if (row1.RowType == DataControlRowType.DataRow)
{
// txtFileType
// txtBData
// txtImageName
TextBox txtFileType, txtBData, txtImageName;
txtFileType = (row1.Cells[1].FindControl("txtFileType") as TextBox);
txtBData = (row1.Cells[1].FindControl("txtBData") as TextBox);
txtImageName = (row1.Cells[1].FindControl("txtImageName") as TextBox);
string constr = ConfigurationManager.ConnectionStrings["CONNECTION"].ConnectionString;
using (SqlConnection con8 = new SqlConnection(constr))
{
string query = "insert into SShare (FId,UDetails,ShareBy,ShareByUserId,BData,FileType,ImageName) values(#FId,#UDetails,#ShareBy,#ShareByUserId,#BData,#FileType,#ImageName)";
using (SqlCommand cmd8 = new SqlCommand(query))
{
cmd8.Parameters.AddWithValue("#FId", txt_Tester.Text);
cmd8.Parameters.AddWithValue("#UDetails", TextBox1.Text);
cmd8.Parameters.AddWithValue("#ShareBy", txt_StaffId.Text);
cmd8.Parameters.AddWithValue("#ShareByUserId", txt_Employee.Text);
cmd8.Parameters.AddWithValue("#BData", txtBData.Text);
cmd8.Parameters.AddWithValue("#FileType", txtFileType.Text);
cmd8.Parameters.AddWithValue("#ImageName", txtImageName.Text);
con8.Open();
// cmd8.ExecuteNonQuery();
this.ExecuteQuery(cmd8, "SELECT");
con8.Close();
}
}
}
}

Here is what I suggest. You could get all the data out of the grid, but you can also just do it in SQL.
Notice BDAta is NOT a SqlParameter, it is pulled from the Employee table:
INSERT INTO [SShare](FId,UDetails,ShareBy,ShareByUserId,BData,FileType,ImageName)
SELECT #FId, #UDetails, #ShareBy, #ShareByUserId, BData, #FileType, #ImageName
FROM Employee
WHERE FId = #FId;

After beating head everywhere atlast I figured out and I am posting it incase if someone may refer to. Thanks to #Crowcoder for giving a logic to make it happen.
foreach (GridViewRow row1 in gvImage.Rows)
{
if (row1.RowType == DataControlRowType.DataRow)
{
string Id = gvImage.DataKeys[row1.RowIndex].Value.ToString();
ImageButton imgbtn = (ImageButton)gvImage.Rows[row1.RowIndex].FindControl("Image2");
string filename = imgbtn.ImageUrl;
TextBox ftype = (row1.FindControl("txtFileType") as TextBox);
byte[] bytes = (byte[])GetData("SELECT BData FROM Employee WHERE Id =" + txt_StaffId.Text).Rows[0]["BData"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgbtn.ImageUrl = "data:image/png;base64," + base64String;
{
string constr = ConfigurationManager.ConnectionStrings["CONNECTION"].ConnectionString;
using (SqlConnection con8 = new SqlConnection(constr))
{
string query = "insert into SShare (FId,UDetails,ShareBy,ShareByUserId,BData,ImageName, FileType) values(#FId,#UDetails,#ShareBy,#ShareByUserId,#BData,#ImageName,#FileType)";
using (SqlCommand cmd8 = new SqlCommand(query))
{
cmd8.Parameters.AddWithValue("#FId", txt_Tester.Text);
cmd8.Parameters.AddWithValue("#UDetails", TextBox1.Text);
cmd8.Parameters.AddWithValue("#ShareBy", txt_StaffId.Text);
cmd8.Parameters.AddWithValue("#ShareByUserId", txt_Employee.Text);
cmd8.Parameters.AddWithValue("#BData", bytes);
cmd8.Parameters.AddWithValue("#ImageName", filename);
cmd8.Parameters.AddWithValue("#FileType", ftype.Text);
con8.Open();
// cmd8.ExecuteNonQuery();
this.ExecuteQuery(cmd8, "SELECT");
con8.Close();
}
}
}
}
}

Related

insert selected image from gridview to mysql table

I use asp.net, c# and mysql.
So how can I insert selected image from gridview to mysql table? Please show me some examples.
The inserted images will be displayed in the GridView control.
The GridView has a OnRowDataBound event handler assigned which will be used for displaying the Image inserted in MySql database.
HTML
<asp:FileUpload ID="FileUpload1"
runat="server" />
<asp:Button Text="Upload"
runat="server"
OnClick="UploadFile" />
<asp:GridView ID="gvImages"
runat="server"
AutoGenerateColumns="false"
OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="File Id"
DataField="FileId" />
<asp:BoundField HeaderText="File Name"
DataField="FileName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1"
runat="server"
Height="80"
Width="80" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO Files(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Content", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
The Above event handler gets executed when the Upload Button is clicked, it first converts the uploaded image file to BYTE array using BinaryReader class and then saves the Image file as Binary data (BLOB) in the MySql Database.
The name of the file, the content type (MIME type) and the actual file as array of bytes are inserted into the MySql database table.
Note: The Content type (MIME type) is very important while downloading the files as it notifies the browser about type of the File.

Multiple Images upload with different titles

My Requirement is. I will be uploading 3-4 images at a time through FileUpload. Each Image will have its own Title, Descriptions etc.
Now my issue is that, whenever uploading I have given a title column for the images. But when I upload 3-4 Images the title and description is going same for all the images.
Here Is my HTML for the Image Uploading via FileUpload.
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label1" runat="server">Image Title</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagetitle" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator1" runat="server"
controltovalidate="txtImagetitle" errormessage="Please add the image title" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label2" runat="server">Image description</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:textbox id="txtImagedesc" cssclass="form-control" runat="server" validationgroup="AddNew"></asp:textbox>
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator2" runat="server"
controltovalidate="txtImagedesc" errormessage="Please add the image description"
validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
<asp:label cssclass="control-label" id="Label3" runat="server">Image upload</asp:label>
</td>
<td>
<div class="control-group">
<div class="controls">
<asp:fileupload id="FileUpload1" runat="server" allowmultiple="true" />
<asp:requiredfieldvalidator cssclass="error-class" id="RequiredFieldValidator3" runat="server"
controltovalidate="FileUpload1" errormessage="Please add the gallery date" validationgroup="AddNew"></asp:requiredfieldvalidator>
</div>
</div>
</td>
</tr>
Please suggest what to do in this case when uploading multiple images how to set different titles for different Images.
UPDATED CODE BEHIND
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
using (SqlConnection conn = new SqlConnection(conString))
if (Request.QueryString["Id"] != null)
{
string Id = Request.QueryString["Id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = " Update tbl_galleries_stack SET gallery_id=#gallery_id,img_title=#img_title,img_desc=#img_desc,img_path=#img_path, IsDefault=#IsDefault Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#gallery_id", ddlgallery.SelectedValue);
cmd.Parameters.AddWithValue("#img_title", txtImagetitle.Text);
cmd.Parameters.AddWithValue("#img_desc", txtImagedesc.Text);
cmd.Parameters.AddWithValue("#img_path", filename);
cmd.Parameters.AddWithValue("#IsDefault", chkDefault.Checked);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery updated sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_galleries_stack (gallery_id,img_title,img_desc,img_path,IsDefault) values(#gallery_id,#img_title, #img_desc, #img_path,#IsDefault)", conn);
cmd1.Parameters.Add("#gallery_id", SqlDbType.Int).Value = ddlgallery.SelectedValue;
cmd1.Parameters.Add("#img_title", SqlDbType.NVarChar).Value = txtImagetitle.Text;
cmd1.Parameters.Add("#img_desc", SqlDbType.NVarChar).Value = txtImagedesc.Text;
cmd1.Parameters.Add("#img_path", SqlDbType.NVarChar).Value = filename;
cmd1.Parameters.Add("#IsDefault", SqlDbType.Bit).Value = chkDefault.Checked;
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery added sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
}
There is no way you can give different title / description as you have given no option to provide it. Period.
You are forced to use multiple fileupload controls. This is also tricky because asp:FileUpload controls wont maintain their state after postback.
So, the solution I can see is a two-part one. Create two panels and hide the second panel at page load
Part 1
Place a label and textbox and button like this in the first panel in your page.
When the user enters a value, say 10, and fires EnterButton_click close Panel1 and open Panel2.
Part 2
On Panel 2, place a GridView like this
<asp:GridView ID="ImagesGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate><%# Container.DisplayIndex + 1 %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:TextBox ID="txtTitle" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:FileUpload ID="flUpload" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="SaveButton" Text="Save" runat="server" OnClick="SaveButton_Click"/>
Now on the Enter buttons click event on Panel 1, write this.
// the idea is to create an empty gridview with number of rows client selected
protected void EnterButton_Click(object sender, EventArgs e)
{
//in this, 10 has been entered
var imageCount = Convert.ToInt32(txtImageCount.Text);
//var list = new List<string>();
//for (int i = 0; i < imageCount; i++)
//{
// list.Add(string.Empty);
//}
var list = new List<string>(10);
list.AddRange(Enumerable.Repeat(String.Empty, imageCount));
ImagesGrid.DataSource = list;
ImagesGrid.DataBind();
//TO DO: hide panel1 and make panel2 visible
}
So on clicking enter, you will get an empty gridview with ten rows.
Now fill the rows in the GridView, do validation and hit Save. On Save Button click event, you can access the WebControls like this.
protected void SaveButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in ImagesGrid.Rows)
{
var title = row.FindControl("txtTitle") as TextBox;
var description = row.FindControl("txtDescription") as TextBox;
var imageFile = row.FindControl("flUpload") as FileUpload;
string filename = Path.GetFileName(imageFile.FileName);
imageFile.SaveAs(Server.MapPath("/GalleryImages/" + filename));
//TO DO: write save routine
}
}
It looks like you only have one set of inputs tied to a single file upload with multiple turned on.
You will either want to turn off multiple and allow the user to add reported sets of those images, or have the editing of title, etc happen in a gridview with the upload.
You could also support a"holding cell " where they upload and then must enter that information before you actually save it to your data store.

Perform a SQL query search based on one or both user inputs and populate a grid view with the results

I am working on a small search form that has two text fields: One that allows users to search for a job list (which is basically a wish list--don't know why they want to call it a "job list" but whatever) by entering in part of or a full email address or someone's first and/or last name (This textbox is called SearchName). This field is required and if it is blank when the user hits "Search," an error message appears telling them so. The second textbox is optional, and it allows users to enter in a city or a state to help narrow their search down even more (this textbox is called SearchLocation).
I have a function (called getJobLists()) that is used by the search button to get results.
As it is right now, the part of the function that returns results based on what is entered into the SearchName field works perfectly. However, I cannot get any results for SearchLocation. When I enter a valid email or name into SearchName, then enter a valid city or state into SearchLocation, I get no results. However, if I enter in anything invalid (i.e. a city that is not associated with the entered email or name) the "no results found" message does appear.
I have tested both SQL queries in my search function in SQL Server Management Studio and they do work perfectly.
I have a try-catch inside the search function, but no error is being shown, not even in the console.
This is the code behind:
protected void Page_Load(object sender, System.EventArgs e)
{
// CHECK IF THE WISHLIST SEARCH ENABLED
StoreSettingsManager settings = AbleContext.Current.Store.Settings;
if (!settings.WishlistSearchEnabled)
{
Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
return;
}
}
protected void getJobLists()
{
try
{
if (SearchName.Text != "")
{//if SearchName.Text is not blank
if (SearchLocation.Text != "")
{//check to see if SearchLocation.Text is not blank either
string sqlSelect = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%') AND ((City + Province) LIKE '%'+#Location+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.Parameters.AddWithValue("#Location", String.Format("%{0}%", SearchLocation.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl = ds.Tables.Add("jobsListsTbl");
jobsListsTbl.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl.NewRow();
dr["User"] = reader["Name"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl";
WishlistGrid.DataBind();
}
}//end of if(SearchLocation.Text !='')
else
{//if SearchLocation.Text is blank, then go with this code instead
string sqlSelect2 = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect2, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl2 = ds.Tables.Add("jobsListsTbl2");
jobsListsTbl2.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl2.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl2.NewRow();
dr["User"] = reader["UserName"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl2.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl2";
WishlistGrid.DataBind();
}
}//end if SearchLocation.Text is empty
}//end of if SearchName.Text !==''
}
catch (Exception x)
{
errors5.Text += "ERROR: " + x.Message.ToString() + "<br />";
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
WishlistGrid.Visible = true;
getJobLists();
}
And this is the designer code for the search form (Note: the NavigateUrl is not set for the hyperlink yet. I will set it once everything is displaying properly for the search results):
<div id="findWishlistPage" class="mainContentWrapper">
<div class="section">
<div class="introDiv">
<div class="pageHeader">
<h1>Find a Job List</h1>
</div>
<div class="content">
<asp:label id="errors" runat="server" text=""></asp:label>
<asp:label id="errors2" runat="server" text=""></asp:label>
<asp:label id="errors3" runat="server" text=""></asp:label>
<asp:label id="errors4" runat="server" text=""></asp:label>
<asp:label id="errors5" runat="server" text=""></asp:label>
<asp:UpdatePanel ID="Searchajax" runat="server">
<ContentTemplate>
<asp:Panel ID="SearchPanel" runat="server" EnableViewState="false" DefaultButton="SearchButton">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableViewState="false" />
<table class="inputForm">
<tr>
<th class="rowHeader">
<asp:Label ID="SearchNameLabel" runat="server" Text="Name or E-mail:" AssociatedControlID="SearchName" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:Textbox id="SearchName" runat="server" onfocus="this.select()" Width="200px" EnableViewState="false"></asp:Textbox>
<asp:RequiredFieldValidator ID="SearchNameValdiator" runat="server" ControlToValidate="SearchName"
Text="*" ErrorMessage="Name or email address is required." EnableViewState="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="rowHeader">
<asp:Label ID="SearchLocationLabel" runat="server" Text="City or State (optional):" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:TextBox id="SearchLocation" runat="server" onfocus="this.select()" Width="140px" EnableViewState="false"></asp:TextBox>
<asp:LinkButton ID="SearchButton" runat="server" CssClass="button linkButton" Text="Search" OnClick="SearchButton_Click" EnableViewState="false" />
</td>
</tr>
</table><br />
<asp:GridView ID="WishlistGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" ShowHeader="true"
SkinID="PagedList" Visible="false" EnableViewState="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderStyle CssClass="wishlistName" />
<ItemStyle CssClass="wishlistName" />
<ItemTemplate>
<asp:HyperLink ID="WishlistLink" runat="server" >
<%#Eval("User")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<HeaderStyle CssClass="wishlistLocation" />
<ItemStyle CssClass="wishlistLocation" />
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("PrimaryAddress")%>'></asp:Label>
<%--'<%#GetLocation(Eval("User.PrimaryAddress"))%>'--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Localize ID="EmptySearchResult" runat="server" Text="There were no job lists matching your search criteria."></asp:Localize>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
Can anyone please tell me what I'm missing or doing wrong?
Okay, I finally solved the issue. Apparently, it was a variable naming issue I kept overlooking. But now it all works okay! :)

Cannot get textbox value from textbox in itemtemplate

The quantity (quantityWanted in DB) in textbox is loaded via Eval() method from Basket DB table. What I want to achieve is that when I change quantity manually and click update the quantity for that record will be updated and then grid will be reloaded. I seem unable to retrieve value of that textbox in code behind.
I am aware of FindControl() method which is used to get value from controls within itemtemplate but I don't know how to use it here.
The tried below but always get nullReferenceException
TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted");
int _quantity = Convert.ToInt16(txt.Text);
Note: button is there but does nothing.
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantityWanted" Text='<%# Eval("quantityWanted") %>' ></asp:TextBox>
<asp:LinkButton ID="LinkButton11" runat="server" CommandName="update" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Update</asp:LinkButton>
<asp:Button ID="Button21" runat="server" Text="Button" CommandName="edit" />
</ItemTemplate>
<asp:TemplateField HeaderText="Total [£]">
<ItemTemplate>
<asp:Label id="lblItemTotal" runat="server" Text='<%# String.Format("{0:C}", Convert.ToInt32(Eval("quantityWanted"))* Convert.ToDouble(Eval("price"))) %>' ></asp:Label>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="remove" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
// .....
else if (e.CommandName == "update")
{
string params = Convert.ToString(e.CommandArgument);
string[] arg = new string[2];
arg = params.Split(';');
name = Convert.ToString(arg[0]);
datetimeAdded = Convert.ToString(arg[1]);
const string strConn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=L:\ASP.NET\Exercise1\Exercise1\Exercise1\App_Data\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
DataSet ds = new DataSet("Employees");
SqlConnection connection = new SqlConnection(strConn);
// Here I need value from textbox to replace 11
SqlCommand abc = new SqlCommand("UPDATE Basket SET quantityWanted = 11 WHERE coffeeName LIKE '%" + name + "%' AND datetimeAdded LIKE '" + datetimeAdded + "' ", connection);
connection.Open();
int ii = abc.ExecuteNonQuery();
connection.Close();
}
}
Use GridView.Rows collection to find control. You can pass the index of row in rows collection indexer.
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
You must pass the row index as well,Your code will look like this
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
I hope it will work for you.
Control ctrl = e.CommandSource as Control;
if (ctrl != null)
{
GridViewRow gvRow = ctrl.Parent.NamingContainer as GridViewRow;
TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted");
}

Displaying Database Images in Gridview with HttpHandler

I am trying to use an ashx page as a http handler for images stored in an SQL server database. These Images are to be displayed in a gridview on an aspx page.
<%# WebHandler Language="C#" Class="LinqHandler" %>
using System;
using System.Web;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public class LinqHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
SqlConnection connect = new SqlConnection();
connect.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT roomID,roomNumber,roomImage1 FROM Rooms "
+ "WHERE roomID = #roomID";
command.CommandType = System.Data.CommandType.Text;
command.Connection = connect;
SqlParameter RoomID = new SqlParameter("#roomID", System.Data.SqlDbType.Int);
RoomID.Value = context.Request.QueryString["roomID"];
command.Parameters.Add(RoomID);
connect.Open();
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["roomImage1"]);
context.Response.ContentType = "image/gif";
dr.Close();
connect.Close();
}
public bool IsReusable {
get {
return false;
}
}
}
for some reason, the images don't bind to the asp:Image control on the aspx page. I'm stumped as to why.
Here is the databinding snippet:
<asp:GridView ID="GridView1" runat="server"
CssClass="gridviews" PagerStyle-CssClass="pager"
DataKeyNames="roomID" AlternatingRowStyle-CssClass="alt"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="roomID" HeaderText="roomID" />
<asp:BoundField DataField="roomNumber" HeaderText="Room Number" />
<asp:TemplateField HeaderText="Image 1">
<ItemTemplate>
<asp:Image runat="server" ID="pic1"
ImageUrl='<%# "~/LinqHandler.ashx?roomID=" + Eval("roomID") %>'>
</asp:Image>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [roomID], [roomNumber], [roomImage1] FROM [Rooms]">
</asp:SqlDataSource>
you can use Handler.ashx for show image. For example:
<img src="Handler.ashx?roomID=1" />
this way you can show image of the one number room.
If you want to do it another way, you can use base64 in css. You dont need to use handler. For example:
<img runat="server" ID="image"/>
//code behind
var bytes = (byte[])dr["roomImage1"]);
var base64String = System.Convert.ToBase64String(bytes, 0, bytes.Length);
image.src = "data:image/gif;base64,"+ base64String;
EDIT:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var bytes = (byte[])((DataRow)e.Row.DataItem)["roomImage1"];
var base64String = System.Convert.ToBase64String(bytes, 0, bytes.Length);
var image = (Image)e.Row.FindControl("pic1");
image.ImageUrl = "data:image/gif;base64,"+ base64String;
//or
image.ImageUrl = "LinqHandler.ashx?roomID="+((DataRow)e.Row.DataItem)["roomID"];
}
}
Try as below:
<ItemTemplate>
<asp:Image ID="pic1" runat="server"
ImageUrl='<%# Eval("roomID", "LinqHandler.ashx?roomID={0}") %>'
Height="100px" Width="80px" />
</ItemTemplate>
It turns out that my problems stem from inserting garbage into my SQL BLOB fields. There is nothing wrong with the retrieval mechanism posted in my source code. If you are curious to see the insert statements I used, let me know and I will be glad to post them.

Categories

Resources