c# asp.net displaying image in gridview - asp.net

I wish to display an image in a gridview.
I have a database with 4 columns - id, author, comment, filename (which holds the img path)
http://postimg.org/image/4loz8t9fb/
I have an image upload method so when the user writes his comment, chooses a photo and clicks submit- his name, the comment and the photo path goes to the database (and the photo itself is uploaded to 'Images' folder in the project folder).
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
Font-Names = "Arial" Height="375px" Width="498px" DataSourceID="SqlDataSource2" >
<Columns>
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
<asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate >
<asp:Image ID="Image1" runat="server" ImageUrl ='<%# Eval("FileName") %>' height="120px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is the c# code-
protected void addcomment_Click(object sender, EventArgs e)
{
string FileName = "";
if (fileupload.PostedFile != null)
{
FileName = Path.GetFileName(fileupload.PostedFile.FileName);
//Save files to disk
fileupload.SaveAs(Server.MapPath("Images/" + FileName));
}
if (TextBox1.Text.Length > 0)
{
string name = firstName + " " + lastName;
SqlCommand cmd = new SqlCommand("insert into comments values(#name,#comment,#filename)", conn);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#comment", TextBox1.Text);
cmd.Parameters.AddWithValue("#filename", Server.MapPath("Images/" + FileName));
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
conn.Close();
TextBox1.Text = "";
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
TextBox1.Text = "You have to type something buddy!";
}
}
The gridview datasource is the sql of course.
Here is an image of the database and the website
http://postimg.org/image/4loz8t9fb/

ImageUrl ='<%# "Images\\"+Eval("FileName") %>'
try this way...

Dont set full path ,
string savepath = "~/Images/" + Filename;
cmd.Parameters.AddWithValue("#filename", savepath));
just change this line it will work
and even change
fileupload.SaveAs(Server.MapPath("~/Images/" + FileName));

in your design view click on smart tag of your gridview and select 'Edit Columns...' then in the opened window create an ImageField and in it's properties on right side of window, under 'Data' pane set the property 'DataImageUrlField' to the field that contains your urls that in this case is 'FileName'. it should works.

Related

How to update database in SQL Server when I have checkbox in gridview?

I tried to make a message board.
After someone leave message, manager can check message context can be show for others or not.
I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.
If I checked checkbox, and click "sent" button, SQL Server data will be updated.
If I would like to update checkbox result into SQL Server data, what should I do?
This is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>
And this is my aspx.cs - if I use foreach, it can't update into my database
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
if (reply.Checked)
{
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1' WHERE (id = {id})", sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close ();
DataBind();
}
}
}
If I use for, it showed error about "datakey array"
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
int messageCheck, displayCheck;
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
if (message.Checked == true)
{
messageCheck = 1;
SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd1.ExecuteNonQuery();
}
else
{
messageCheck = 0;
SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd2.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
Without javascript, how could I do it?
Thanks for you all
Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.
However, for templated columns, we have to use find control.
And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.
Ok, so here is a GV with both datafiles (the cells()), and also check box.
We will select the check boxes, and then with a save button, send changes back to database.
So, our markup:
<div style="width:50%;padding:25px">
<asp:GridView ID="GVHotels" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save changes" CssClass="btn"/>
</div>
And now our code to fill out above could be say this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we see this:
Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.
but, we just loop the GV, and execute updates. (if I have time, I'll try and post the 2nd more cool approach).
So, our button to update/save changes (for check boxes). Could be this:
protected void cmdSave_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
conn.Open();
string strSQL = "UPDATE tblHotels Set Smoking = #S, Balcony = #B " +
"WHERE ID = #ID";
foreach (GridViewRow gRow in GVHotels.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
}
Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.
Note that you would continue to use cells() collection for NON templated columns. But for any templated column - you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.
We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows - we actually keep the connection open for the update - and thus not a big deal either way.
Kindly check with this code
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each row In GridView1.Rows
Dim chk As CheckBox = row.FindControl("CheckBox2")
If chk.Checked Then
'sql update query
Else
End If
Next
End Sub

How to display uploaded image file in grid from a folder in the root?

Aspx.vb code which i am using to save data in a folder.
Try
Dim j As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
Dim PathName As String
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
PathName = System.IO.Path.GetFileName(hpf.FileName)
Dim BookingNumber As String = objWHParent.WHImageTabList.ToList().Item(i).BookingNumber
Dim FileName As String = BookingNumber + "_WRH_" + (i.ToString()) + PathName
hpf.SaveAs(Server.MapPath("~/UploadedImages\") & FileName)
objWHParent.WHImageTabList.ToList().Item(i).FilePath = FileName
objWHParent.WHImageTabList.ToList().Item(i).Flag = "Warehouse"
End If
Next
Catch generatedExceptionName As Exception
Throw
End Try
After uploading i want to display each image uploaded behind the browse button in the grid
You need to add image control on gridview and give URL from your Data source. Please see below code for reference:
<asp:GridView ID="gvFolder" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageURL") %>'Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Textinfo Not posting to .mdb file. Not sure why

I am currently stumped on a particular issue which I need your help. I'm having this particular issue with my asp.net website.
For whatever reason when a user is trying to save information from a text box to my .mdb file it's not accepting it. Everything compiles fine and I have quadruple checked all of the ID and string names and everything appears to match with what it should on the table in the .mdb, the .c file, and the aspx.cs pages.
Here is the .aspx page that the information is input on
<asp:Label ID="lblFirstName1" runat="server" align="left" Text="First Name: " Width="125px"></asp:Label>
<asp:TextBox ID="txtfirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtfirstName" ErrorMessage="First Name cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblLastName1" runat="server" Text="Last Name: " Width="125px"></asp:Label>
<asp:TextBox ID="txtlastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtlastName" ErrorMessage="Last Name cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblUserAddress1" runat="server" Text="Street Addres: " Width="125px"></asp:Label>
<asp:TextBox ID="txtstreetAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtstreetAddress"
ErrorMessage="Address cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblcity1" runat="server" Text="City: " Width="125px"></asp:Label>
<asp:TextBox ID="txtcity" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtcity"
ErrorMessage="City cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblstate1" runat="server" Text="State: " Width="125px"></asp:Label>
<asp:TextBox ID="txtstate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtstate"
ErrorMessage="State cannot be empty"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblzipCode1" runat="server" Text="Zip Code: " Width="125px"></asp:Label>
<asp:TextBox ID="txtzipCode" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="txtzipCode"
ErrorMessage="Zip Code cannot be empty"></asp:RequiredFieldValidator>
here is the info from the .cs page that it is using to save to the .mdb
public static bool Saveneworder(string Database, string firstName, string lastName, string streetAddress, string city, string state, string zipCode )
{
bool recordSaved;
// Create a new Oledb Transaction object
OleDbTransaction myTransaction = null;
try
{
// Create a New Connection Object to the Access Database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// set the transaction object and start the transaction
myTransaction = conn.BeginTransaction();
command.Transaction = myTransaction;
strSQL = "Insert into tblOrder " +
"(firstName, lastName, streetAddress, city, state, zipCode) values ('" +
firstName + "', '" + lastName + "', '" + streetAddress + "', '" + city + "', '" + state +
"', '" + zipCode + "')";
// set the command text of the command object
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Execute the insert statement
command.ExecuteNonQuery();
myTransaction.Commit();
// Close the Database connection
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
//Rollback the transaction if some failure occurs
myTransaction.Rollback();
recordSaved = false;
}
return recordSaved;
}
Here is the first aspx.cs files that transfers the data from the textboxes to the orderverified page that lists the else statement that the information did not post
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (ValidateFields()) //if Validate fields method has returned true
{
Session.Add("txtfirstName", txtfirstName.Text);
Session.Add("txtlastName", txtlastName.Text);
Session.Add("txtstreetAddress", txtstreetAddress.Text);
Session.Add("txtcity", txtcity.Text);
Session.Add("txtstate", txtstate.Text);
Session.Add("txtzipCode", txtzipCode.Text);
Server.Transfer("orderverified.aspx");
}
and it forwards the information to this aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
//So here we are initializing text property of the textbox "txtVerifiedInfo" after fetching the
//values from the session object
txtVerifiedInfo.Text = Session["txtfirstName"].ToString() +
"\n" + Session["txtlastName"].ToString() +
"\n" + Session["txtstreetAddress"].ToString() +
"\n" + Session["txtcity"].ToString() +
"\n" + Session["txtstate"].ToString() +
"\n" + Session["txtzipCode"].ToString()
;
// Check if the record is successfully saved in the tblOrder Table and prints the appropriate message in the text box txtVerifiedInfo
if (clsDataLayer.Saveneworder(Server.MapPath("App_Data\\WSC_DB.mdb" ),
Session["txtfirstName"].ToString(),
Session["txtlastName"].ToString(),
Session["txtstreetAddress"].ToString(),
Session["txtcity"].ToString(),
Session["txtstate"].ToString(),
Session["txtzipCode"].ToString() ))
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe Order successfully submitted!";
}
else
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\n The order did not save, please return to the previous screen and verify all of your data is correct, thank you.";
}
On the last page - Orderverified.aspx i have a multiline text box that clearly shows all of the data but it is returning my else statement that it was not able to save to the tblOrder
sorry for posting so much code but I really am stumped on why this isn't saving.
Thank you for reading and for your time
Upon further troubleshooting i have tried excluding everything EXCEPT for the firstName and it still will not post.
i feel the problem is most likely with the .cs files code that is the sql statement to insert into the tblOrder
I've never used OleDbConnection, but it seems you may need to use .Parameters.AddWithValue().
See this StackOverflow answer.
Okay, I figured it out - I couldnt find an issue with any of the code because there wasnt one!!
I turns out i had the primary key int he .mdb set as a field that i was not inputting to and it was causing it not to save because it was set to text instead of autonumber and would not let the file save!! thank you for taking a look at it jeremywho

direct link to image in database in asp.net

How can we retrieve an image from database with direct link?
I understand that we can get the image as /getImage.aspx?id=1 for instance.
But how can we create a direct link like /image1.jpg ?
you can use URL Rewrite to solve your problem
YOU SHOULD TRY THIS
<asp:GridView ID="GridView1" runat="server" EnableViewState="false"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" />
<asp:BoundField HeaderText="File Name" DataField="FileName" />
<asp:TemplateField HeaderText="File">
<ItemTemplate> <img src="ShowImage.ashx?autoId=<%# Eval("AutoId") %>" alt="<%#
Eval("FileName") %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate> <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Behind Code:
string _connStr =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFiles();
}
}
private void BindFiles()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "SELECT AutoId, FileName, FileContent, Active FROM Files
Order By AutoID ASC";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}

DataGrid and MultiBind

I'm new to ASP.NET and are struggling with displaying data in a GridView. I got most of it working with help from this forum. Currently I'm trying to build a file name from an ID and a "file extension" from a database, but got stuck. I guess I need to use MultiBind to get this working? My file name is ID + "_tn" + file extension, and this is my code.
<asp:GridView ID="HitGridView" runat="server" onrowdatabound="HitsRowBid">
<Columns>
<asp:TemplateField HeaderText="Street">
<ItemTemplate>
<asp:TextBox ID="Adress" runat="server" width="200" Text='<%# Bind("StreetName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton ID="defaultImg" runat="server" ImageUrl='<%# Bind("ImgId") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind
protected void HitsRowBid(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgBtn = (ImageButton)e.Row.FindControl("defaultImg");
imgBtn.ImageUrl = "Content/FileUpload/" + imgBtn.ImageUrl + "_tn" + ".jpg";
}
}
But how do I get the file extension that is stored in the database?
I mainly use ListViews, but there are a couple of ways to accomplish this. One way would be to use DataKeys when databinding and retrieve the value by using the row index in the onrowdatabound event. Another option would be to write a helper method in codebehind and call it during databinding, something like:
protected string FormatImagePath(string fileName)
{
string imagePath = Request.ApplicationPath.TrimEnd('/') + "/previews/" + fileName;
FileInfo testFile = new FileInfo(Helpers.BaseSiteFilePath + #"previews\\" + fileName);
if (!testFile.Exists)
{
imagePath = Request.ApplicationPath.TrimEnd('/') + "/images/no_preview.png";
}
return imagePath;
}
Calling it like such:
ImageUrl='<%# FormatImagePath(Eval("PreviewURL").ToString()) %>'

Resources