I am adding Select Checkbox at every row in GridView while loading from database. Below is my aspx page code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="100%" onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Number">
<ItemTemplate>
<asp:Label ID="lblpn" runat="server" Text='<%# Eval("PartNumber") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Part Desc">
<ItemTemplate>
<asp:Label ID="lblpd" runat="server" Text='<%# Eval("PartDesc") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to read the data from the rows which are selected in the respective Checkbox.
For this I have done following code in Button Click:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow dr = GridView1.Rows[i];
Label lblID = (Label)dr.FindControl("lblid");
ID = Convert.ToInt32(lblID.Text);
CheckBox checkBox = (CheckBox)dr.FindControl("cbSelect");
if (checkBox.Checked)
{
}
}
Now if I select single row in grid then I am able to get the checkbox status Checked for that particular row.
But If I select multiple rows then I am getting only first selected row's checkbox status as checked.
From second row I am getting Check status as Unchecked. But I am able to get correct value in lblID label control.
Following is my function to fill gridview:
public void showgrid(string Location)
{
DataTable dt = new DataTable();
con.Open();
string strQuery = "";
SqlDataAdapter sda = new SqlDataAdapter();
if (chkConsiderPart.Checked)
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "' and PartNumber='" + ddlPartNumber.SelectedItem.Text + "'";
else
strQuery = "select * from InventoryDetails where Status='Stocked' and ToLocation='" + Location + "'";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
if (dt.Rows.Count == 0)
{
lblRowsStatus.Text = "No Records found for the selection.";
}
else
{
lblRowsStatus.Text = "There are " + dt.Rows.Count.ToString() + " Records found for the selection.";
}
}
I am only calling it in:
if (!IsPostBack)
{
showgrid(ddlFromLocation.SelectedItem.Text);
}
Also there was post-back at certain events of other controls. but even if I removed them same issue is happening.
Note: There is no code written in any of Gridview Events.
I am trying to use grid view to display a join of several tables(Empdetail,Department,Country,State,City,Qualification). The main table(Empdetail) has different IDs(eg DeptID) which refer to the primary key ID present in the tables. I want department(and other fields) to appear as dropdown choice while updating the gridview but I am facing issues while populating the drop down list and making the edit button fire. The following is the code.
.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Database.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employee Database</title>
<script src="Themes/js/bootstrap.js" type="text/javascript"></script>
<script src="Themes/js/jquery.min.js" type="text/javascript"></script>
<script src="Themes/js/npm.js" type="text/jahttp://www.aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspxvascript"></script>
<script src="Themes/js/bootstrap.min.js" type="text/javascript"></script>
<script type = "text/javascript" src = "Scripts/jquery-1.3.2.min.js"></script>
<script type = "text/javascript" src = "Scripts/jquery.blockUI.js"></script>
<script type = "text/javascript">
//to create a loading effect
function BlockUI(elementID) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function() {
$("#" + elementID).block({ message: '<table align = "center"><tr><td>' +
'<img src="Images/loadingAnim.gif"/></td></tr></table>',
css: {},
overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'
}
});
});
prm.add_endRequest(function() {
$("#" + elementID).unblock();
});
}
$(document).ready(function() {
BlockUI("dvGrid");
$.blockUI.defaults.css = {};
});
</script>
<link href="Themes/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap-theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id = "dvGrid">
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "900px" AlternatingRowStyle-BackColor = "#b3e6ff"
AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound"
HeaderStyle-BackColor = "#0080ff" DataKeyNames="ID"
PageSize="10" class="table table-bordered" ShowFooter="true"
onrowediting="EditEmployee" onrowupdating="UpdateEmployee"
onrowcancelingedit="CancelEdit" OnRowDeleting="DeleteEmployee"
EmptyDataText="No records Selected.">
<Columns >
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%# Eval("ID") %>' /><!--Primary key,no update and insert,auto generated-->
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "EmpCode">
<ItemTemplate>
<asp:Label ID="lblEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmpCode" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "DOJ">
<ItemTemplate>
<asp:Label ID="lblDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDOJ" class="form-control" Width = "100px"
MaxLength = "15" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "120px" HeaderText = "Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server"
Text='<%# Eval("DeptName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox class="form-control" ID="txtDepartment" Width = "140px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%# Eval("CoName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCountry" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server"
Text='<%# Eval("SName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtState" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%# Eval("CiName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCity" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Qualification">
<ItemTemplate>
<asp:Label ID="lblQualification" runat="server"
Text='<%# Eval("QName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQualification" class="form-control" Width = "80px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("ID")%>' OnClick = "DeleteEmployee"
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" >
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
class="btn-primary" type="button" OnClick = "AddNewEmployee"/>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Codebehind(aspx.cs/c#)
using System;
using System.Collections;
using System.Collections.Generic;
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.Xml.Linq;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
//Find the DropDownList in the Row
SqlConnection con = new SqlConnection(constr);
DropDownList Depddl = (DropDownList)e.Row.FindControl("Depddl");
string query = "SELECT ID,DeptName FROM Department;";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
Depddl.DataSource = GetData(cmd);
Depddl.DataTextField = "DeptName";
Depddl.DataValueField = "ID";
Depddl.DataBind();
con.Close();
//Add Default Item in the DropDownList
Depddl.Items.Insert(0, new ListItem("Please select"));
//Select the Department ofEmployee in DropDownList
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
}
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string city = (GridView1.Rows[e.RowIndex].FindControl("Depddl") as DropDownList).SelectedItem.Value;
string ID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblID")).Text;
string EmpCode = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtEmpCode")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string DOJ = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtDOJ")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Empdetail set EmpName=#EmpName," + "EmpCode=#EmpCode,"+ "DOJ=#DOJ where ID=#ID; " +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, "+
"Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID "+
"JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID "+
"JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = EmpCode;
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#DOJ", SqlDbType.VarChar).Value = DOJ;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Empdetail where " +
"ID=#ID;" +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private void BindData()
{
string query = "select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ,"+
"Department.ID, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID"+
" JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID"+
" JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void AddNewEmployee(object sender, EventArgs e)
{
string ID = ((TextBox)GridView1.FooterRow.FindControl("txtID")).Text;
string EmpCode = ((TextBox)GridView1.FooterRow.FindControl("txtEmpCode")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
/*cmd.CommandText = "insert into Empdetail(EmpCode, CompanyName) " +
"values(#CustomerID, #ContactName, #CompanyName);" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value = CustomerID;
cmd.Parameters.Add("#ContactName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Company;*/
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
Note:- I have searched extensively and on multiple sites so I would really appreciate it if you can tell me the exact issue instead of navigating me to a link. I am new to the concept of Gridview so please critique the code with an open mind. Thanks in advance
In the aspx file I'd drop data sources for each dropdown, SqlDataSource for example. In the markup you can fully define each DDL and every row uses the same single instance of the datasource. On editing you need only capture the selected value to update.
So...the DataSource for the Department example...
. . .
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="SELECT ID,DeptName FROM Department"
EnableCaching="True">
</asp:SqlDataSource>
Then in the GridView Template for Department...
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
DataSourceID="SqlDataSource1"
DataTextField="DeptName"
DataValueField="ID"
</asp:DropDownList>
</EditItemTemplate>
And in the code behind you can optionally select the current value for the DDL from a current value...or not...up to you.
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( e.Row.RowState.HasFlag( DataControlRowState.Edit ) )
{
DataRowView drv = (DataRowView) e.Row.DataItem;
DropDownList ddl = (DropDownList) e.Row.FindControl( "DropDownList1" );
ddl.SelectedValue = ((int) drv[ "ID" ]).ToString();
}
}
}
After commenting several segments of the code I realized that the issue was with the "OnRowDataBound" function.
Commenting these lines made the update button fire again:-
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
What I could gather from this is that I cannot access an Item template control that way. Commenting the lines made the page run smoothly. However it was at the cost of losing the functionality of auto-selecting the original data value. I would like to implement this and will post an update as soon as I can achieve this.
Following is my code... I am trying to store image in database. I have used varbinary(MAX) datatype for storing data bytes in database. Please tell me where I am going wrong.
int qtype = Convert.ToInt32(ddl_q_Type.SelectedValue);
var getQ = (from q in obj.QuestionRegistrations
orderby q.QueCode ascending
where q.QueQuesType == qtype && q.QueLanguageCode == 1
select new { q.QueCode, q.QueQuestion }
).ToArray();
index = Convert.ToInt32(ViewState["index"].ToString()) + 1;
ViewState["index"] = index;
previosIndex = index - 1;
ViewState["previosIndex"] = previosIndex;
txt_question.Text = getQ[index].QueQuestion;
lblqcode.Text = getQ[index].QueCode.ToString();
int qcode = Convert.ToInt32(lblqcode.Text);
var options = (from opt in obj.QuestionAndOptionsMappings
where opt.QueMapQuestionCode == qcode
select new { opt.QueMapOptions, opt.QueMapCorrectAnswer, opt.QueMapId, opt.QueMapImage }
).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("QueMapOptions", typeof(string));
dt.Columns.Add("QueMapId", typeof(string));
dt.Columns.Add("QueMapImage", typeof(string));
foreach (var y in options)
{
DataRow dr = dt.NewRow();
dr["QueMapOptions"] = y.QueMapOptions;
dr["QueMapId"] = y.QueMapId;
dr["QueMapImage"] = (Byte[])y.QueMapImage;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
This code for storing the image in databse
for (int i = 0; i < GridView1.Rows.Count; i++)
{
FileUpload fp = (FileUpload)GridView1.Rows[i].Cells[2].FindControl("fp");
Label lblmapid = (Label)GridView1.Rows[i].Cells[1].FindControl("lblmapid");
bool e1 = fp.HasFile;
int mapiidd = Convert.ToInt32(lblmapid.Text);
if (fp.HasFile)
{
string path = Server.MapPath("~/Uploads/") + fp.FileName;
fp.SaveAs(path);
byte[] imageBytes =
File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/") + fp.FileName);
int qcodelbl = Convert.ToInt32(lblqcode.Text);
QuestionAndOptionsMapping qmap = new QuestionAndOptionsMapping();
var update = obj.QuestionAndOptionsMappings.Where(q => q.QueMapId == mapiidd && q.QueMapQuestionCode == qcodelbl)
;
update.SingleOrDefault().QueMapImage = imageBytes;
obj.SaveChanges();
}
}
ASPX code
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="OPTIONS" HeaderStyle-Width="55%">
<ItemTemplate>
<asp:TextBox ID="Option" runat="server" Text='<%#Eval("QueMapOptions") %>' Height="40px"
Width="500px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%" Visible="false">
<ItemTemplate>
<asp:Label ID="lblmapid" runat="server" Text='<%#Eval("QueMapId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:CheckBox ID="Chk_correct_Ans" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:FileUpload ID="fp" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub Section" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("QueMapImage") %>' Height="80px"
Width="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok, you can't just bind a binary column to a GridView column. you need to make use of Response.BinaryWrite method.
Here are few steps to follow to achieve what you want
Create a generic handler to read binary data. We'll call it ImageHandler.ashx. Make sure you have the primary key of the table to be passed to this handler. Write the handler code something like below (just an example).
public void ProcessRequest (HttpContext context)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
And call the handler like this.
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'
instead of
ImageUrl='<%#Eval("QueMapImage") %>'
Here's a complete example from where I extracted above examples.
All the best!
here i want to have no.of coloumns i have checked and deleted in lable
i have used following code to execute my query of deleting multiple values in gridview using checkbox
here is my code and script part
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
grd_bnd();
}
}
private void grd_bnd()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from student", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
grd_bnd();
}
}
and here is script
<asp:GridView ID="GridView1" runat="server" DataKeyNames="rollno" AllowSorting="true" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkboxdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat ="server" Text='<%#Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No.">
<ItemTemplate>
<asp:Label ID="lblrollno" runat ="server" Text='<%#Eval("rollno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="lblbatch" runat ="server" Text='<%#Eval("batch") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblcourse" runat ="server" Text='<%#Eval("course") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
<asp:Button ID="Button3" runat="server" Font-Bold="True" Text="Delete Selected" ForeColor="#000066" OnClick="Button3_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="#666666"></asp:Label>
i wanna get the number of entities deleted in above lable , lable1.
Simply add a count before your loop
protected void Button3_Click(object sender, EventArgs e)
{
int rows = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
rows += cmd.ExecuteNonQuery(); //Can return 0 if no rows were deleted!
con.Close();
cmd.Dispose();
}
}
grd_bnd();
MessageBox.Show(String.Format("Rows affected {0}", rows);
}
You can use the return value of ExecuteNonQuery:
int numDeleted = cmd.ExecuteNonQuery();
MSDN: returns the number of rows affected.
If you want the total rows use a variable:
int totalNumDeleted = 0;
foreach (GridViewRow row in GridView1.Rows)
{
// ...
int numDeleted = cmd.ExecuteNonQuery();
totalNumDeleted += numDeleted;
}
Label1.Text = string.Format("{0} students were deleted successfully.", totalNumDeleted);
The sorting works fine when u fill the gridview using SQL datasource in the aspx page...
but now i am using template field and the columns are filled separately in the codebehind and the sorting is not working...
my code is
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
ondatabound="GridView1_DataBound"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="File Name" ItemStyle-Width="40%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Failure Count" ItemStyle-Width="10%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns></GridView>
and my codebehind is:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT FileName,FailureCount from Files where MachineID=#strID , connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("strID", strID);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string nameoffiles = dt.Rows[i]["FileName"].ToString();
buFailureCode.Add(code);
string count = dt.Rows[i]["BuFailureCount"].ToString();
buFailureCount.Add(count);
}
}
connection.Close();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (namesOfFiles.Count != 0)
{
for (int i = 0; i < namesOfFiles.Count; i++)
{
GridViewRow myRow = GridView1.Rows[i];
Label Label1 = (Label)myRow.FindControl("Label1");
Label Label3 = (Label)myRow.FindControl("Label3");
Label1.Text = namesOfFiles[i].ToString();
Label3.Text = buFailureCount[i].ToString();
}}}
set SortExpression
I think you'll have to handle the OnSorting event and do the actual sorting yourself in code-behind. The API documentation has an example.