I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.
Here is the code that I used
.aspx code
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<h2>Employee Details</h2>
</td>
</tr>
<tr>
<td>ID</td>
<td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>BloodGroup</td>
<td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Emergency Contact No.</td>
<td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Photo:</td>
<td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />
<asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />
<asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'
Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Image_upload
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileuploadEmpImage.HasFile)
{
int length = fileuploadEmpImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadEmpImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
int id = Convert.ToInt32(txtID.Text);
string name = txtName.Text;
string bloodGroup = txtBloodGroup.Text;
string phoneNo = txtContactNo.Text;
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtBloodGroup.Text = string.Empty;
txtContactNo.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
BindGridData();
}
}
}
private void BindGridData()
{
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
grdEmployee.DataSource = dt;
grdEmployee.DataBind();
}
}
}
handler.ashx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Image_upload
{
public class Employeeimage_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
MySqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.
To fix your code introduce MySqlParameters:
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
var connection = new MySqlConnection(
ConfigurationManager.ConnectionString["database"]);
connection.Open();
// remove the order by and add a where with a parameter placeholder
var command = new MySqlCommand(
"select ImageI from database.employee where id = #id",
connection);
// setup parameter and add to command
command.Parameters.AddWithValue("#id", imageid);
// execute
MySqlDataReader dr = command.ExecuteReader();
// rest of your code
}
Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files
Related
I have a record update page which seems to populate all the fields, however the dropdown lists will only list the data from that particular record, it is not listing the other School Names and the Student Names. The two dropdown lists are cascaded i.e. selecting the School Name ddl should list only the Students that are from that school in the Student ddl.
Any help on this will be much appreciated, thank you.
Gridview code on tours.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging" OnEditCommand="EditAddress" PageSize="5">
<Columns>
<asp:HyperLinkField Text="Update" DataNavigateUrlFields="TourId" DataNavigateUrlFormatString="~/abcrud1/tours_update.aspx?TourId={0}" />
<asp:BoundField DataField="TourId" HeaderText="TourId" HtmlEncode="false" />
<asp:BoundField DataField="VisitorName" HeaderText="VisitorName" HtmlEncode="false" />
<asp:BoundField DataField="VisitorSchoolId" HeaderText="VisitorSchoolId" HtmlEncode="false" />
<asp:BoundField DataField="SchName" HeaderText="SchName" HtmlEncode="false" />
<asp:BoundField DataField="TourDate" HeaderText="TourDate" HtmlEncode="false" />
<asp:BoundField DataField="StudentId" HeaderText="StudentId" HtmlEncode="false" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" HtmlEncode="false" />
<asp:BoundField DataField="LastName" HeaderText="LastName" HtmlEncode="false" />
</Columns>
</asp:GridView>
tour_update.aspx
<form id="form1" runat="server">
<div>
<table style="width: 50%;">
<tr>
<td style="width: 50%;">Tour Id:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourid" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor Name:</td>
<td style="width: 50%;">
<asp:TextBox ID="txtvisname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor School:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlvisschool" runat="server" AutoPostBack="true"></asp:DropDownList></td>
</tr>
<tr>
<td style="width: 50%;">Tour Date:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourdate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Student:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlstudent" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td><asp:Button ID="btnUpdate" Text="Update" runat="server" OnClick="TourUpdate_click" /></td>
<td></td>
</tr>
</table>
</div>
</form>
tour_update.aspx.cs
{
public partial class tours_update : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
{
if (!IsPostBack)
{
this.GetTour();
}
}
}
protected void TourUpdate_click(object sender, EventArgs e)
{
this.TourUpdate();
}
private int id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["TourId"]) ? int.Parse(Request.QueryString["TourId"]) : 0;
}
}
private void TourUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE tblCRUD1_Tour SET VisitorName=#VisitorName, VisitorSchoolId=#VisitorSchoolId, TourDate=#TourDate, StudentId=#StudentId WHERE TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.SelectedItem.Value);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.SelectedItem.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/abcrud1/tours.aspx");
}
}
}
private void GetTour()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName
FROM tblCRUD1_Tour
INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId
INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId
WHERE tblCRUD1_Tour.TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
this.txttourid.Text = dr["TourId"].ToString();
this.txtvisname.Text = dr["VisitorName"].ToString();
this.txttourdate.Text = dr["TourDate"].ToString();
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "VisitorSchoolId";
ddlvisschool.DataBind();
ddlstudent.DataSource = dt;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
}
}
}
}
}
}
}
tours_add.aspx.cs
{
public partial class tours_add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddlvisschool();
ddlstudent.Items.Insert(0, " Select Pupil ");
}
}
private void Bindddlvisschool()
{
con.Open();
string str = #"Select * FROM tblCRUD1_School ORDER BY SchName ASC";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "SchId";
ddlvisschool.DataBind();
ddlvisschool.Items.Insert(0, new ListItem(" Choose Last School ", "0"));
ddlvisschool.SelectedIndex = 0;
con.Close();
}
protected void TourAdd_click(object sender, EventArgs e)
{
con.Open();
string str = #"INSERT INTO tblCRUD1_Tour (VisitorName,VisitorSchoolId,TourDate,StudentId) VALUES (#VisitorName,#VisitorSchoolId,#TourDate,#StudentId)";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.Text);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.Text);
cmd.ExecuteNonQuery();
lblmessage1.Text = "Tour added successfully";
con.Close();
Response.AddHeader("REFRESH", "3;URL=tours.aspx");
}
protected void ddlvisschool_SelectedIndexChanged(object sender, EventArgs e)
{
string get_SchId;
string get_SchName;
get_SchId = ddlvisschool.SelectedValue.ToString();
get_SchName = ddlvisschool.SelectedItem.Text;
if (get_SchId != "0")
{
con.Open();
SqlDataAdapter da;
DataSet ds = new DataSet();
string query;
query = "SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName "
+ "FROM tblCRUD1_Tour "
+ "INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId "
+ "INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId "
+ "WHERE tblCRUD1_Tour.VisitorSchoolId='" + get_SchId.ToString() + "' ORDER BY tblCRUD1_Student.LastName ASC";
da = new SqlDataAdapter(query, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ddlstudent.DataSource = ds;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
//ddlstudent.Items.Insert(0, new ListItem(get_SchName.ToString(), "0"));
ddlstudent.SelectedIndex = 0;
}
else
{
ddlstudent.Items.Insert(0, "No Student");
ddlstudent.DataBind();
}
}
}
}
}
So I have the data table filled but the column I need image data in is not working. I can see the table filled and can see it is reading the data, but not as a byte array, nor is it displaying the image.
public void Bindformview()
{
try
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
And I know I need to insert this code, or something like it that pulls the data out of the db "thumbnail varbinary(MAX)" column as a byte stream, to get the byte array for the image to display properly:
DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";
table.Columns.Add(column); //Add the column to the table.
and this:
DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);
But I do not need a new column or a new row as those fields are already there.
So how to I fill column "Thumbnail" in the data table, with byte array data to display and where do I do the insert of said code, before the if statement that loads the dt, in the if statement that binds the dt?
do I do it by stating the column like so:
dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());
and then put this in to fill the formview image1 ID like so?
string strBase64 = Convert.ToBase64String(bytes);
formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;
I am just at a standstill and not sure how to do this.
So to be clear, I already have the DB with the Proper image info, and can display it by <asp:image id=image1...etc />, with other code that retrieves the image outside of the formview using this code,
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetImageByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
}
but it doesn't work in a <asp:FormView...etc/> and I need to be able to have it do so for page formating.
This is why I was going in this direction, of using a Data Table right now. If you have a better solution I am open to trying it, as long as it can be used inside of the <asp:formview /> element. Thank you.
So I figured it out:
I Needed to add an Object o; and this line after the databind o = dt.Rows[0]["RecipeId"];
Like So:
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
and made the call to load the image as so:
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Here is the code below if anyone else needs to do the same thing. I will be putting together a for/while or for/next for going through multiple data base entries to display at the same time instead of one at a time currently in this <asp:forview...></formview> element setup.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;
namespace DB_Test1
{
public partial class Search_Results_1 : System.Web.UI.Page
{
string b;
Object o;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Search"] != null)
{
if (Request.QueryString["Text"] != null)
{
string a = Request.QueryString["Text"];
b = a;
recipeSearch(a);
}
}
}
protected void recipeSearch(string a)
{
//Search the database
con.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
catch (Exception ex)
{
//throw new ApplicationException("operation failed!", ex);
}
con.Close();
FormViewRecipes.Visible = true;
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Image1.Visible = true;
}
protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
string a = b;
FormViewRecipes.PageIndex = e.NewPageIndex;
recipeSearch(a);
}
}
}
And here is the ASPX page code:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<hr />
<div class="row">
<div class="col-md-8">
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
</td>
<td>
<asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
<%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
<ItemTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
<%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>'
AlternateText='<%# Eval("ThumbnailAltTxt") %>'
Height="100px" Width="100px" />--%></td>
</tr>
<tr><td><b>Title:- </b></td><td>
<asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
<tr><td><b>Ingredients:- </b></td><td>
<asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>
<tr><td><b>Directions:- </b></td><td>
<asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
<tr><td><b>Notes:- </b></td><td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>
</table>
</ItemTemplate>
<EmptyDataTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
<tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
</table>
</EmptyDataTemplate>
</asp:FormView>
</td>
</tr>
</table>
</div>
<div class="col-md-4">
<p>Ad Space</p>
<asp:Label ID="lblDataTable" runat="server"></asp:Label>
</div>
</div>
</asp:Content>
Just remember I commented out the <asp:image..../a> element field that is in the <Asp:formview.../> element and reset my page layout to get how I wanted it to look for testing.
I am retrieving Data From Database into GridView.
I don't know how to Edit and Delete row in GridView and it Also Update in Database.
Also please Tell me if their is any mistake in my Code
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 248px;
}
.style2
{
width: 100%;
}
.style3
{
height: 180px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style3">
<h1 align="center">Students Personal Information
</h1>
<table class="style2">
<tr>
<td class="style1">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Button ID="Button1" runat="server" Text="Insert Data"
onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Students" Width="128px" />
</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
enter code here
And my back-end code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=DATA_NET_81_SOF;Initial
Catalog=Students;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Student's Name";
Label2.Text = "Student's Class";
Label3.Text = "Student's Roll Number";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", conn);
conn.Open();
cmd.Parameters.AddWithValue("StudentName", TextBox1.Text);
cmd.Parameters.AddWithValue("StudentClass", TextBox2.Text);
cmd.Parameters.AddWithValue("StudentRollno", TextBox3.Text);
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand sql = new SqlCommand("Select * from Personalinfo", conn);
SqlDataAdapter da = new SqlDataAdapter(sql);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = (ds);
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
}
private string connection = #"...";
protected void Button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connection))
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
}
For Update -->
protected void Button_Update(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "UPDATE Personalinfo SET StudentName = #1 ... WHERE Student_Id= #N";
cmd.Parameters.Add("#1",SqlDbType.NVarChar).Value = your_value;
cmd.Para.....
cmd.Parameters.Add("#N",.....).Value = your_student_id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
For Delete -->>
protected void Button_Delete(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Personalinfo WHERE StudentName = '"+TextBox1.Text+"'";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
After every event of button you can make a BindGrid ... to refresh your data from data grid... in BindGrid method you need to remake the select method you just did ... if you have issue tell me
I've a listview that allows Editing and Delete.
When I Click on the linkbutton in the listview, it fires up page_load then to OnItemCommand.
At the end of the command I added DataBind Which does not refresh my listview but deleted my entry.
If I change the DataBind to Redirect back to the same page with (...aspx?ID=...) it will return me a fresh new page. but in debug mode, I saw it run through page_load and the Databind.
<asp:UpdatePanel ID="UpdateOptions" runat="server" >
<ContentTemplate>
<asp:Panel ID="OPanel" runat="server" width="350px">
<asp:ListView runat="server" ID="lvPollOptions" DataKeyNames="POptionID" OnItemCommand="lvPollOptions_ItemCommand" OnDataBound="lvPollOptions_ItemDataBound" >
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="300px">
<tr class="AdminListHeader">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("OptionText")%>
</td>
<td>
<%#Eval("Votes")%>
</td>
<td align="center">
<asp:ImageButton runat="server" ID="ibtnEditOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Edit" ImageUrl="~/images/buttons/EditPencil.gif" AlternateText="Edit" CssClass="AdminImg" />
</td>
<td>
<asp:ImageButton runat="server" ID="ibtnDeleteOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Delete" ImageUrl="~/images/buttons/delete.gif" AlternateText="Delete" CssClass="AdminImg" OnClientClick="return confirm('Warning: This will delete the Poll Option from the database.');" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Label ID="lblNoOption" runat="server" Text="No Options Added"></asp:Label>
<table width="345px">
<tr>
<td width="100px">
Option:
</td>
<td>
<asp:TextBox ID="txtOption" runat="server" width="200px"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
string PID = Request.QueryString["ID"];
if (!IsPostBack)
{
if (PID == null)
{
}
else if (PID != null)
{
PollBindData();
}
}
}
protected void lvPollOptions_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string PID = Request.QueryString["ID"];
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void lvPollOptions_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string selectedID = e.CommandArgument.ToString();
SqlConnection connDeleteOption = new SqlConnection(connStr);
connDeleteOption.Open();
SqlCommand cmdDeleteOption = new SqlCommand("DELETE FROM [PollOptions] WHERE POptionID = '" + selectedID + "'", connDeleteOption);
cmdDeleteOption.ExecuteNonQuery();
connDeleteOption.Close();
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + selectedID);
}
if (e.CommandName == "Edit")
{
string EditID = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmdView = new SqlCommand("SELECT OptionText From [PollOptions] Where POptionID = '" + EditID + "'", conn);
SqlDataReader dr1 = cmdView.ExecuteReader();
if (dr1.Read())
{
txtOption.Text = dr1["OptionText"].ToString();
}
Session["OptionID"] = txtOption.Text;
dr1.Close();
conn.Close();
lbOInsert.Visible = false;
lbOUpdate.Visible = true;
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + EditID);
}
}
Before we start - your code has a security risk since it is prone to Sql Injection, make sure you Parametrize your queries...
Now, your question is not very clear, but if I understand correctly, you're saying that after you delete an object, the Listview isn't refreshed after postback (e.g. you still see the deleted item). Since you're running in an UpdatePanel, make sure to update the panel after the DataBind...
Update PoolBindData like this
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
// POTENTIAL SECURITY RISK - MAKE SURE YOU PARAMETRIZE THE QUERY!!
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataTable dsSel = new DataTable();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
// Update panel
UpdateOptions.Update();
}
I have an ASP.NET FileUpload control. In the code-behind file, I used class to insert values-
public void Insertcert()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
if (FileUpload1.HasFile)
{
byte[] productImage = FileUpload1.FileBytes;
String insertstring2 = #"insert into Cert(CertName, CertLogo)
values(#CertName, #CertLogo)";
SqlCommand cmd = new SqlCommand(insertstring2, conn);
cmd.CommandText = insertstring2;
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#CertName", TextBox18.Text);
cmd.Parameters.Add("#CertLogo", SqlDbType.VarBinary).Value = productImage;
cmd.ExecuteNonQuery();
}
}
finally
{
conn.Close();
}
Executing it here-
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
Insertcert();
}
I am using Wizard control to insert Certifications of the Employee:
<asp:Wizard ID="Wizard1" runat="server"
OnFinishButtonClick="Wizard1_FinishButtonClick"
Width="266px" ActiveStepIndex="0">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Step 2">
<asp:Label ID="Label19" class="caption" runat="server" Text="Certification Name:"></asp:Label>
<asp:TextBox ID="TextBox18" class="box" runat="server"></asp:TextBox> <br /><br />
<asp:Label ID="Label20" class="caption" runat="server" Text="Certification Logo:"></asp:Label>
<asp:FileUpload ID="FileUpload1" class="box" runat="server" /> <br /><br />