Problem with download files from databases through GridView - asp.net

I have problem with files. I'm trying to download files from databases
through gridview, but after I download them, they are with wrong name and extensions. Their name are my web form name and their extensions are .aspx.
In the database they are saved in the correct format.
Here are my code-behind
public partial class data : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["DecumentsConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillData();
}
}
private void FillData()
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getDecuments", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo filename = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = filename.Name;
string extnt = filename.Extension;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("savedocument", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#Content", documentContent);
cmd.Parameters.AddWithValue("#extn",extnt);
con.Open();
cmd.ExecuteNonQuery();
}
}
private void Donwload(int id)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getdocument", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", id);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
string name = dt.Rows[0]["name"].ToString();
byte[] document = (byte[])dt.Rows[0]["DocumentContent"];
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Dispisition", string.Format("attachment;filename={0}", name));
Response.AddHeader("Content-Lenght", document.Length.ToString());
Response.BinaryWrite(document);
Response.Flush();
Response.Close();
}
protected void OpenDocument(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lnk.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());
Donwload(id);
}
}
}
and my html
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Document"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
<br />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Documents">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="OpenDocument" runat="server" Text='<%# Eval("name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
img

Related

Show Images from Database ASP.Net

I am new to ASP.net and have some problem to show images. My designer code is as bellow.
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src="../images/companylogo.png" alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
My code behind code is as bellow.
protected void ShowImageFile(object sender, EventArgs e)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + id).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Problem: how to set table:wrapper1 img src in code behind because it does not shown in code behind. I tried to do with Image1 but its also not accessing in code behind.
Please help me.
Thanks, Raja
Try Like this
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img id="myimage" runat="server" src="../images/companylogo.png" />
</td>
</tr>
</table>
</div>
You can access Src from Code Behind
Try like this
'Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);
foreach (DataRow row in dt.Rows)
{
// Get the byte array from image file
byte[] imgBytes = (byte[])row["logo"];
// If you want convert to a bitmap file
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes );
string imgString = Convert.ToBase64String(imgBytes);
// Set the source with data:image/bmp
myimage.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}
EDIT
Access Image inside GridView
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
Image imgCtrl = (Image) args.Row.FindControl("imgCtrl");
imgCtrl.ImageUrl = m_ConcatUrl;
}
}
(or)
private string m_ConcatUrl;
protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
{
if(args.Row.RowType == DataControlRowType.DataRow)
{
HtmlImage img = (HtmlImage) args.Row.FindControl("imgCtrl");
imgCtrl.Src= m_ConcatUrl;
}
}
You can try following way:
HTML:
<div id="directory-logo-wrapper" class="floatright">
<table id="wrapper1" runat="server">
<tr>
<td>
<img src='<%# ImageUrl(ProjectId) %>' alt="LogoWrapper" />
<%--<asp:Image ID="Image1" runat="server" Visible="true" alt="LogoWrapper" />--%>
</td>
</tr>
</table>
</div>
Code Behind:
private string ImageUrl(int ProjectId)
{
byte[] bytes = {};
bytes = (byte[])GetData("SELECT UploadedLogo FROM Projects WHERE ProjectId =" + ProjectId).Rows[0]["UploadedLogo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
return "data:image/png;image/jpg;base64," + base64String;
//Image1.ImageUrl = "data:image/png;image/jpg;base64," + base64String;
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConnectionInfo.GetConnectionString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Hope this helps.

checkbox_oncheckedchange event not firing in a gridview

I am trying to populate a gridview from a datatable in the code behind. In one of the columns dynamic checkboxes are generated. This is the code for gridview:
<asp:GridView ID="grdAdDetails" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField HeaderText="Ad Id" DataField="Ad Id" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="Ad Type" DataField="Ad Type" />
<asp:TemplateField HeaderText="Ad">
<ItemTemplate>
<img src='<%#Eval("Ad") %>' height="150px" width="150px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Ad Url" DataField="Ad Url" />
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
**<asp:CheckBox ID="chkAds" Checked='<%#((bool)Eval("Active"))%>' runat="server" OnCheckedChanged="chkAds_OnCheckedChanged" />**
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField HeaderText="Active" DataField="Active" />--%>
<asp:BoundField HeaderText="Node Id" DataField="Node Id" />
</Columns>
</asp:GridView>
and this is the datatable code from the code behind:
DataTable dt = new DataTable();
dt.Columns.Add("Ad Id", typeof(string));
dt.Columns.Add("Ad Type", typeof(string));
dt.Columns.Add("Ad", typeof(string));
dt.Columns.Add("Ad Url", typeof(string));
dt.Columns.Add("Active", typeof(bool));
dt.Columns.Add("Node Id", typeof(string));
DataRow dr = dt.NewRow();
con.Open();
SqlCommand cmd = new SqlCommand("[temp].[somename]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#nodeId", 1088);
cmd.Parameters.AddWithValue("#adType", 0);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
dr["Ad Id"] = reader[0].ToString();
dr["Ad Type"] = reader[1].ToString();
dr["Ad"] = reader[2].ToString();
dr["Ad Url"] = reader[3].ToString();
dr["Active"] =Convert.ToBoolean(reader[4]);
dr["Node Id"] = reader[5].ToString();
}
dt.Rows.Add(dr);
}
con.Close();
grdAdDetails.DataSource = dt;
grdAdDetails.DataBind();
checkbox onchanged code:
public void chkAds_OnCheckedChanged(object sender, EventArgs e)
{
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
CheckBox cb = (CheckBox)grdAdDetails.Rows[selRowIndex].FindControl("chkAds");
if (cb.Checked)
{
//some code here
}
}
When I check/uncheck the checkbox, the OnCheckedChanged event is not firing. Can anyone help with that?
I have added a sample here plz chk it.
view:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false"
OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:checkbox id="CheckBox1" runat="server" AutoPostBack="true" oncheckedchanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Name">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("fpath")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%#Eval("desc1")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtdesc" runat="server" Text='<%#Eval("desc1")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText="Edit">
<ControlStyle Width="50" />
</asp:CommandField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this record?');">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
String fname, fpath, desc;
String spath;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
if (!Page.IsPostBack)
{
LoadGrid();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//Check File is available in Fileupload control and then upload to server path
fname = FileUpload1.FileName;
spath = #"~\Uploaded\" + FileUpload1.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + FileUpload1.FileName;
desc = TextBox2.Text;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
FileUpload1.SaveAs(fpath);
}
//Store details in the SQL Server table
StoreDetails();
TextBox2.Text = "";
LoadGrid();
}
else
{
Label1.Text = "Please select file!";
}
}
void StoreDetails()
{
String query;
query = "insert into fileDet(fname,fpath,desc1) values('" + fname + "','" + spath + "','" + desc + "')";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}
void LoadGrid()
{
sqlcon.Open();
sqlcmd = new SqlCommand("select * from fileDet", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.DataBind();
}
sqlcon.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
LoadGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
LoadGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String ID;
ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
sqlcmd = new SqlCommand("select * from fileDet where ID='" + ID + "'", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (System.IO.File.Exists(Server.MapPath(dt.Rows[0][2].ToString())))
{
System.IO.File.Delete(Server.MapPath(dt.Rows[0][2].ToString()));
}
}
sqlcmd = new SqlCommand("delete from fileDet where ID='" + ID + "'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
string ID;
ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
FileUpload flname = (FileUpload)row.FindControl("FileUpload2");
if (flname.HasFile)
{
fname = flname.FileName;
spath = #"~\Uploaded\" + flname.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + flname.FileName;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
flname.SaveAs(fpath);
}
}
else
{
Label1.Text = "Please select file!";
}
TextBox desc1 = (TextBox)row.FindControl("txtdesc");
string query;
query = "update fileDet set fname='" + fname + "',fpath='" + spath + "',desc1='" + desc1.Text + "' where ID='" + ID + "'";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
GridView1.EditIndex = -1;
LoadGrid();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
// lblmsg.Text = GridView1.DataKeys[gr.RowIndex].Value.ToString();
//lblmsg.Text = "Hello";
}
}

bind image from database to datalist

I am binding image to datalist.
My imagename is in database, i am taking it and wants to bind it to datalist.
I have tried following:
<asp:DataList ID="dlImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# Bind ("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
on pageload i have bounded it as:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
In above code ds is my dataset and gc.GetDataToListBinder(query) returns dataset.
But images are not getting displayed.
What can be the mistake?
EDIT1:
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg")) %>' runat="server" />
Take a minute and read this:
http://www.codeproject.com/Articles/142013/There-is-something-about-Paths-for-Asp-net-beginne
I think this will help you alot.
EDIT:
For the space problem, take a look:
Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?
Basically:
ImageUrl='<%# Server.HtmlDecode(Bind("MyImage")) %>'
But i recommend that you store your image name without space in db.
EDIT2:
ImageUrl='<%# Eval("MyImage") %>'
ImageUrl='<%# Server.HtmlDecode(Eval("MyImage")) %>'
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" CellPadding="2"
CellSpacing="2"
UseAccessibleHeader="True" >
<ItemTemplate>
<asp:ImageButton Width="120" Height="120" ID="Image1" ImageUrl='<%# Eval("Imgpath", "") %>' runat="server" />
</asp:Datalist>
.CS
SqlConnection con;
SqlCommand cmd;
string strCon = "Connection String";
SqlDataAdapter da;
protected void AlldataImg()
{
DataTable dt = new DataTable();
string strQuery = "select code,imgpath from SA_Stock order by Code";
cmd = new SqlCommand(strQuery);
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
da.Dispose();
con.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
AlldataImg();
}
Put Image Path in database too so that image will appear..
protected void DataListPosts_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
Image ImageData = (Image)e.Item.FindControl("ImageData");
if (dr.Row[4].ToString() != "NA")
{
ImageData.Visible = true;
ImageData.ImageUrl = #"ImgPost/" + dr.Row["ImgPath"].ToString();
}
else
ImageData.Visible = false;
}
}
catch (Exception)
{ }
}
its a old topic but i think it can be usefull for anyone
firstly get your data from string
string sqlget = "select Photo from Promoter";
and get it to database dsget
then do that
dsget.Tables[0].Columns.Add("Photopath", typeof(string));
for (int i = 0; i < dsget.Tables[0].Rows.Count; i++)
{
if (dsget.Tables[0].Rows[i]["Photo"].ToString() != null && dsget.Tables[0].Rows[i]["Photo"].ToString() != "")
{
var data = (Byte[])(dsget.Tables[0].Rows[i]["Photo"]);
var stream = new MemoryStream(data);
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
FileBytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(FileBytes, 0, FileBytes.Length);
dsget.Tables[0].Rows[i]["Photopath"] = "data:image/png;base64," + base64String;
}
}
DataList1.DataSource = dsget.Tables[0];
DataList1.DataBind();
in asp file write the following thing

validation in datagrid while insert update in asp.net

Untitled Page
<telerik:GridTemplateColumn Visible="false">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%# bind("pid") %>'>
</asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn UniqueName="Fname" HeaderText="Fname" DataField="Fname" CurrentFilterFunction="NotIsNull" SortExpression="Fname">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Lname" HeaderText="Lname" DataField="Lname" CurrentFilterFunction="NotIsNull" SortExpression="Lname">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Designation" HeaderText="Designation" DataField="Designation" CurrentFilterFunction="NotIsNull" SortExpression="Designation">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="column">
</telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<FormTemplate>
<table>
<tr>
<td>Fname*</td>
<td>
<asp:HiddenField ID="Fname" runat="server" Visible="false" />
<asp:TextBox ID="txtFname" runat="server" Text='<%#("Fname")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="EvalFname" ControlToValidate="txtFname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Lname*</td>
<td>
<asp:HiddenField ID="HiddenField1" runat="server" Visible="false" />
<asp:TextBox ID="txtLname" runat="server" Text='<%#("Lname")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtLname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Designation*
</td>
<td>
<asp:HiddenField ID="HiddenField2" runat="server" Visible="false" />
<asp:TextBox ID="txtDesignation" runat="server" Text='<%#("Designation")%>'>
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtDesignation" ErrorMessage="Enter Designation" runat="server" ValidationGroup="Update">
*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</FormTemplate>
<EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">
</EditColumn>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
</form>
this is my code i want to perform validation using the required validators but i think m missing smthin so pls help,
here's my code behind
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Telerik.Web.UI;
public partial class Default7 : System.Web.UI.Page
{
string strQry;
public SqlDataAdapter da;
public DataSet ds;
public SqlCommand cmd;
public DataTable dt;
string strCon = "Data Source=MINETDEVDATA; Initial Catalog=ML_SuppliersProd; User Id=sa; Password=#MinetApps7;";
public SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
dt = new DataTable();
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
try
{
strQry = "SELECT * FROM table2";
con.Open();
da.SelectCommand = new SqlCommand(strQry,con);
da.Fill(dt);
RadGrid1.DataSource = dt;
}
finally
{
con.Close();
}
}
protected void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
con = new SqlConnection(strCon);
cmd = new SqlCommand();
GridDataItem item = (GridDataItem)e.Item;
string pid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["pid"].ToString();
con.Open();
string delete = "DELETE from table2 where pid='"+pid+"'";
cmd.CommandText = delete;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem radgriditem = e.Item as GridEditableItem;
string pid = radgriditem.OwnerTableView.DataKeyValues[radgriditem.ItemIndex]["pid"].ToString();
string firstname = (radgriditem["Fname"].Controls[0] as TextBox).Text;
string lastname = (radgriditem["Lname"].Controls[0] as TextBox).Text;
string designation = (radgriditem["Designation"].Controls[0] as TextBox).Text;
con = new SqlConnection(strCon);
cmd = new SqlCommand();
try
{
con.Open();
string update = "UPDATE table2 set Fname='" + firstname + "',Lname='" + lastname + "',Designation='" + designation + "' WHERE pid='" + pid + "'";
cmd.CommandText = update;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to update Reason: " + ex.Message));
e.Canceled = true;
}
}
protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
{
GridEditFormInsertItem insertitem = (GridEditFormInsertItem)e.Item;
string firstname = (insertitem["Fname"].Controls[0] as TextBox).Text;
string lastname = (insertitem["Lname"].Controls[0] as TextBox).Text;
string designation = (insertitem["Designation"].Controls[0] as TextBox).Text;
con = new SqlConnection(strCon);
cmd = new SqlCommand();
try
{
con.Open();
String insertQuery = "INSERT into table1(Fname,Lname,Designation) Values ('" + firstname + "','" + lastname + "','" + designation + "')";
cmd.CommandText = insertQuery;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to insert Reason:" + ex.Message));
e.Canceled = true;
}
}
}
Does your button have the same ValidationGroup value as your Validator controls?

Pls modify this code for retrieving the image from sqldatabase

I am still suffering from retrieving an image from a SQL database. This is my final solution for inserting and retrieving an image from database. Here is all my code:
GUI part:
<div>
<asp:Label ID="lblImage" runat="server" Text="Image"></asp:Label>
<asp:FileUpload ID="imageUpload" runat="server" />
<br />
<asp:Label ID="lblFilename" runat="server" Text="Filename"></asp:Label>
<asp:TextBox ID="txtFilename" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="BtnSave" runat="server" Text="SAVE" onclick="BtnSave_Click" />
<br />
<br />
<br />
<asp:Image ID="Image1" runat="server" />
</div>
And under the Button click event i have written the following code:
protected void BtnSave_Click(object sender, EventArgs e)
{
string uploadFileName = string.Empty;
byte[] imageBytes = null;
if (imageUpload != null && imageUpload.HasFile)
{
uploadFileName = imageUpload.FileName;
imageBytes = imageUpload.FileBytes;
}
string str = ConfigurationManager.ConnectionStrings["ImageConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand("INSERT INTO REPORT_TABLE (IMAGEFIELD,IMAGENAME) VALUES (#image,#filename)", con);
com.Parameters.Add("#image", SqlDbType.Image, imageBytes.Length).Value = imageBytes;
com.Parameters.Add("#filename", SqlDbType.VarChar, 50).Value = uploadFileName;
con.Open();
com.ExecuteNonQuery();
con.Close();
SqlConnection conn = new SqlConnection(str);
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
**this.pictureBox1.Image = Image.FromStream(ms)**; //(This code is for a Windows application but I want to retrieve an image from a web application) so what should be written instead of the highlighted code? In imagecontrol, image id is Image1.
}
you can server image like this:
.....
Image img= Image.FromStream(ms);
Response.Clear();
Response.ContentType = "image/jpeg";
img.Save(Response.OutputStream, ImageFormat.Jpeg);
}
but this will not put image in the <asp:Image ID="Image1" runat="server" /> because it needs image url not the image object :(
what you can do is setup a separate page to serve image and pass it image id or other unique identifier associated with image to show it in the <asp:Image ID="Image1" runat="server" />. simply add new page to your solution say ImageServer.aspx and in page_load write following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasValues())
{
var id=Request.QueryString["id"];
if(!string.IsEmptyOrNull(id))
{
SqlConnection conn = new SqlConnection(str);
//CHANGE SELECT TO GET ONLY IMAGE WITH PASSED ID
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
Response.Clear();
Response.ContentType = "image/jpeg";
var img=system.Drawing.Image.FromStream(ms);
img.Save((Response.OutputStream, ImageFormat.Jpeg);
Response.Flush();
return;
}
//HERE YOU MAY RETURN DEFAULT OR ERROR IMAGE
}
}
Now change you button click in upload page as follows:
protected void BtnSave_Click(object sender, EventArgs e)
{
....
//SAVE IMAGE TO DB AND GET IMAGE ID (TO IDENTIFY THIS IMAGE)
image.ImageUrl = "YOUR_SERVER\ImageServer.aspx?id=" + IMAGE_ID;
}

Resources