How to Edit / change a File Uploaded with another Uploaded File in asp.net Webforms? - asp.net

net webforms CRUD project where I've created textboxes, dropdown menu and a File upload for people to enter their details & I'm using them in a Grid-View, only doc docx and pdf are allowed, and I've created an edit button on the same Grid-View along with the delete button when I Press on Edit Button it opens up the edit menu for making changes in their details and they can also choose items from dropdown and can upload new file as well.
I'm trying to catch the files name to store it into db using a sp but I'm not getting any details its showing this error :-
enter image
protected void custgrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
int id = Convert.ToInt32(custgrid.DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("sp_update", con);
string fname = (custgrid.Rows[e.RowIndex].FindControl("txtFname") as TextBox).Text;
string num = (custgrid.Rows[e.RowIndex].FindControl("txtNum") as TextBox).Text;
string cv = (custgrid.Rows[e.RowIndex].FindControl("cvv") as TextBox).Text;
string qual = (custgrid.Rows[e.RowIndex].FindControl("ddlQual") as TextBox).Text;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#cv", cv);
cmd.Parameters.AddWithValue("#qual", qual);
cmd.Parameters.AddWithValue("#number", num);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Read();
}
}
here's my code, am I doing something wrong? Please Tell me how can I fix it.
I'm trying to make it possible for other to be able to upload new files when in edit mode. But it's showing the error mentioned the the question above.

Related

Retrieving images from SQL Server 2008 and displying it in a image controller of asp.net

I have a table images in SQL Server 2008 and it contains two columns imageid and image. I am able to insert images into the image column using the FileUpload controller and image which I have converted to binary form for storing. Now I want to display the images in an image box corresponding with the image id. I am using a textbox for having the user type in the id and a button to execute the command for displaying.
public void ShowImage()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["anu"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ID,Image from Images where ID=" + txtid.Text;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader dreader = cmd.ExecuteReader();
dreader.Read();
Context.Response.BinaryWrite((byte[])dreader["image"]);
dreader.Close();
con.Close();
}
This code is working fine but it loads the image in a separate page but I need to display it in a particular image box. My front end is ASP.NET. If any one knows the answer, please help me.
Instead of Response.Write Store the byte array in a session
Session["image"]=(byte[])dreader["image"];
Use this as the the source of your image
byte[] imgSrc=(byte[])Session["image"]
string imgSrcStr= Convert.ToBase64String(imgSrc);
string imageSrc = string.Format("data:image/gif;base64,{0}", imgSrcStr);
In the view:
<img src='"<%=imageSrc%>"' />
Or simply do all this in your function itself instead of Response
First you should really use a parameter in your query (or a stored procedure)
And you can just create an Image from the binary data and save that to the outputstream with the correct imageformat.
var ms = new MemoryStream((byte[])dreader["image"]);
var image = Image.FromStream(ms);
Context.Response.ContentType = "image/jpeg"; //or your actual imageformat
image.Save(Context.Response.OutputStream, format);

How to use drill down functionality using pop up window in ASP.Net (Fusion Charts)

I am using a drill down functionality where i can click the bar chart and it will open new page with the new child chart. But i what i don't want is to open a new window, all what i want is to use a pop up window with the child chart in it. I have seen some example from fusion-chart website but they are using xml format and i cannot follow their example. Here is my entire code which is working fine but the only thing i need to change instead of opening a new page; i just need to use a pop up window. How can i do that? pls help and thanks for your time..
here is my main page code:
//aspx code
<asp:Literal ID="chart_from_db" runat="server">
</asp:Literal>
//code behind
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
StringBuilder xmlStr = new StringBuilder();
xmlStr.Append("<chart caption='Total Revenue' palette='3' showValues='0' numberPrefix='$' useRoundEdges='1'>");
{
string sqlStatement = "SELECT Category, AvgNumbers FROM Table1";
SqlCommand cmd = new SqlCommand(sqlStatement, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
xmlStr.AppendFormat("<set label='{0}' value='{1}' link='{2}'/>", reader["Category"].ToString(), reader["AvgNumbers"].ToString(), Server.UrlEncode("DrillDown1.aspx?AvgDays=" + reader["Category"].ToString()));
}
xmlStr.Append("</chart>");
reader.Close();
con.Close();
FusionCharts.SetRenderer("javascript");
chart_from_db.Text = FusionCharts.RenderChart(
"FusionChartsXT/Column3D.swf", // Path to chart's SWF
"", // Page which returns chart data. Leave blank when using Data String.
xmlStr.ToString(), // String containing the chart data. Leave blank when using Data URL.
"annual_revenue", // Unique chart ID
"640", "340", // Width & Height of chart
false, // Disable Debug Mode
true); // Register with JavaScript object
}
And here is child page that opens up when the chart is clicked.
// ASPX code
<div>
<asp:Literal ID="MyChart" runat="server">
</asp:Literal>
//code benind
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
String AvgDays = Request.QueryString["AvgDays"];
StringBuilder xmlStr = new StringBuilder();
xmlStr.Append("<chart caption='Total Revenue' palette='3' showValues='0' numberPrefix='$' useRoundEdges='1'>");
{
string sqlStatement = "select MonthYear, AvgNumbers from Table2 where AvgDays= '" + AvgDays.ToString() + "'";
SqlCommand cmd = new SqlCommand(sqlStatement, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Construct the chart data in XML format
xmlStr.AppendFormat("<set label='{0}' value='{1}' link='{1}'/>", reader["MonthYear"].ToString(), reader["AvgNumbers"].ToString());
}
// End the XML string
xmlStr.Append("</chart>");
// Close the result set Reader object and the Connection object
reader.Close();
con.Close();
// Set the rendering mode to JavaScript, from the default Flash.
FusionCharts.SetRenderer("javascript");
// Call the RenderChart method, pass the correct parameters, and write the return value to the Literal tag
MyChart.Text = FusionCharts.RenderChart(
"FusionChartsXT/Column3D.swf", // Path to chart's SWF
"", // Page which returns chart data. Leave blank when using Data String.
xmlStr.ToString(), // String containing the chart data. Leave blank when using Data URL.
"crab", // Unique chart ID
"640", "340", // Width & Height of chart
false, // Disable Debug Mode
true); // Register with JavaScript object
}
please refer the link below.,.
http://docs.fusioncharts.com/charts/contents/JavaScript/JS_LinkedCharts.html
-LinkedCharts in ExtJS window
-Opening LinkedCharts in jQuery PrettyPhoto
-Opening LinkedCharts in jQuery dialog
I hope... this may help you!

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

How to display mysql blob image in asp.net image control?

I known the way to display the mysql blob image in Windows Forms.
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select logo from mcs_institude where id = 1";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
pictureBox1.Image = new Bitmap(new MemoryStream((byte[])Reader.GetValue(0)));
}
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in Get_ImageFormDB"+ ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
But now i doing a asp.net project. In this image not have the image property,.
command = connection.CreateCommand();
command.CommandText = "Select FO_Roomdet_Image from fo_roomtype where FO_Roomdet_Id=1";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
Image1.ImageUrl = new MemoryStream((byte[])Reader.GetValue(0));
}
connection.Close();
When i try this in asp.net, it through an error.
Error 1 Cannot implicitly convert type 'System.IO.MemoryStream' to
'string'
How Can i Solve this issue. and get mysql blob image just display in asp.net image control.
help me please.
What you're trying to do doesn't make sense: the browser trying to display your image will need to know where to download it from.
You should setup a special aspx page, dedicated to image generation, for example GetImage.aspx.
Your main page will then have img html tags pointing to this image generation page:
<img src="/GetImage.aspx?id=your_image_id"/>
Then, inside GetImage.aspx, you retrieve the image from DB according to its id (fetched from URL parameter). The code would be something like:
command = connection.CreateCommand();
command.CommandText = "Select FO_Roomdet_Image from fo_roomtype where FO_Roomdet_Id=1"; // or dynamically fetch id with Request.QueryString and properly escape it
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
Response.ContentType = "image/jpeg"; // if your image is a jpeg of course
Response.BinaryWrite((byte[])Reader.GetValue(0));
}
connection.Close();
Well, this is definetely not the simplest answer.
You do not need to create an extra aspx file to image generation and re-generation each time when it's used.
You can actually embed the image files into the html markup language by it's byte array.
All you need to do is get the BLOB byte array from your database and use this:
<img src="data:image/png;base64,<%= System.Convert.ToBase64String((byte[])dr["img"])%>" />
...where dr is a DataRow obtained from a DataSet object.
I have tested it in Internet Explorer 8 and all modern browsers and it works.

ASP.NET store Image in SQL and retrieve for Asp:Image

I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :
// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImageID", conn))
{
command.Parameters.Add("#ImageID", SqlDbType.Int).Value = imageId;
conn.Open();
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:
<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />
That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.
If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.
After a few hundred gigabytes of images, I believe you'll find yourself thinking that the operating systems' file system and static file http servers is better suited than the database, which is busy which a lot of other details, for storing images. It also allows you to use thousands of existing free tools to work with, move, host, etc the images.
Instead of storing images in the database, store the path and/or filename for the image. Images will fill up the database and make it slow.
protected void Page_Load(object sender, EventArgs e) {
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e) {
string strImageName = txtImageName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "File Uploaded";
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
con.Close();
}
}
Try these links it might help you..
you can also try by storing the image files on the server and store the paths on the Sql table..
by these links
http://pratikataspdotnet.blogspot.in/2014/11/retrieve-images-from-path-stored-in.html

Resources