checkbox_oncheckedchange event not firing in a gridview - asp.net

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";
}
}

Related

Problem with download files from databases through GridView

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

How to add new row in a gridview on button click

I am new to asp.net and i want to add new row in a gridview on button click... see my code kindly help me..its been 2 days i am working on it but didn't find the solution....
HTML CODE
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
DataKeyNames="PRODUCTID" CellPadding="3" GridLines="Both" OnRowEditing="gridOnRowEditing"
OnRowCancelingEdit="gridOnRowCancelingEdit" OnRowUpdating="gridOnRowUpdating">
<HeaderStyle BackColor="Cyan" ForeColor="White" BorderColor="Red" />
<Columns>
<asp:CommandField ButtonType="Button" ShowCancelButton="true" ShowEditButton="true"
HeaderText="Edit & Update" />
<asp:BoundField DataField="PRODUCTID" HeaderText="PRODUCT ID" ReadOnly="true" />
<asp:TemplateField HeaderText="PRODUCT NAME">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtProduct1" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtProduct" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIT PRICE">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtPrice1" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPrice" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" OnClick="button1_click" ID="button1" Text="Add New Row" />
<%-- <input type="button" id="btnNew" value="Add New" onclick="addNew()" />--%>
</div>
C SHARP CODE
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=practice;Integrated Security=true;");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From PRODUCTDETAILS order by PRODUCTID asc", con);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["CurrentTable"] = dt;
}
protected void gridOnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridOnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void gridOnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox txtProductName = (TextBox)row.FindControl("txtProduct");
TextBox UNITPRICE = (TextBox)row.FindControl("txtPrice");
string ProductName = txtProductName.Text;
string txtUnitPrice = UNITPRICE.Text;
int ProductID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
UpdateRecord(ProductID, ProductName, txtUnitPrice);
}
protected void UpdateRecord(int ProductID, string ProductName, string UnitPrice)
{
try
{
SqlCommand cmd = new SqlCommand("Update PRODUCTDETAILS set ProductName=#ProductName,UnitPrice=#UnitPrice WHERE ProductID=#ProductID", con);
cmd.Parameters.Add(new SqlParameter("#ProductID", ProductID));
cmd.Parameters.Add(new SqlParameter("#ProductName", ProductName));
cmd.Parameters.Add(new SqlParameter("#UnitPrice", UnitPrice));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
catch (Exception ex)
{
throw ex;
}
}
protected void AddNewRow()
{
//dt = new DataTable();
//DataRow dr = null;
//dt.Columns.Add(new DataColumn("PRODUCTID", typeof(string)));
//dt.Columns.Add(new DataColumn("PRODUCTNAME", typeof(string)));
//dt.Columns.Add(new DataColumn("UNITPRICE", typeof(string)));
//dr = dt.NewRow();
//dr["PRODUCTID"] = 14;
//dr["PRODUCTNAME"] = string.Empty;
//dr["UNITPRICE"] = string.Empty;
//dt.Rows.Add(dr);
//ViewState["CurrentTable"] = dt;
//GridView1.DataSource = dt;
//GridView1.DataBind();
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
int ProductID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
TextBox TextBoxName = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtProduct1");
TextBox TextBoxPrice = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtPrice1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["PRODUCTID"] = ProductID + 1;
drCurrentRow["PRODUCTNAME"] = TextBoxName.Text;
drCurrentRow["UNITPRICE"] = TextBoxPrice.Text;
//dtCurrentTable.Rows[13 - 1]["PRODUCTID"] = ProductID + 1;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
protected void button1_click(object sender, EventArgs e)
{
AddNewRow();
}
}
}

Gridview fields values does not change on update

I have a gridview and i want to modify some fields on gridview.This fields value not change when i click on Update button.I tried use Postback control but this problem keep going.How can i solve this problem?
ASPX code
<asp:GridView ID="gview" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" GridLines="Horizontal" OnRowDataBound="gview_RowDataBound" OnRowEditing="gview_RowEditing" OnRowUpdating="gview_RowUpdating" OnRowCancelingEdit="gview_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="SubCategoryId" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="SubCategoryId" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCategory" DataValueField="CategoryId" DataTextField="CategoryName" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:CommandField ButtonType="Link" EditText="Edit" HeaderText="Edit"
ShowEditButton="True" ShowHeader="False" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:GridView>
C# code
protected void gview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = e.Row.FindControl("lblCategory") as Label;
DropDownList ddl = e.Row.FindControl("ddlCategory") as DropDownList;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddl.DataSource = LoadCategories();
ddl.DataBind();
}
if (lbl != null)
{
lbl.Text = GetCategoryName(Convert.ToInt32(gview.DataKeys[e.Row.RowIndex][0]));
}
}
}
protected void gview_RowEditing(object sender, GridViewEditEventArgs e)
{
gview.EditIndex = e.NewEditIndex;
SubCategoryLoad();
}
protected void gview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int categoryId, subCategoryId;
string categoryName;
DropDownList ddl = (DropDownList)gview.Rows[e.RowIndex].FindControl("ddlCategory");
subCategoryId = int.Parse(gview.Rows[e.RowIndex].Cells[0].Text);
categoryId = int.Parse(ddl.SelectedValue);
categoryName = gview.Rows[e.RowIndex].Cells[2].Text;
gview.EditIndex = -1;
UpdateSubCategory(subCategoryId,categoryName,categoryId);
SubCategoryLoad();
}
public void SubCategoryLoad()
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "SELECT * FROM dbo.SubCategories";
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
da.Fill(dt);
gview.DataSource = dt;
gview.DataBind();
}
}
}
public int UpdateSubCategory(int subCategoryId, string categoryName, int categoryId)
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "UPDATE dbo.SubCategories SET CategoryId = #categoryId, CategoryName = #categoryName WHERE SubCategoryId = #id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#id", subCategoryId);
cmd.Parameters.AddWithValue("#categoryName", categoryName);
cmd.Parameters.AddWithValue("#categoryId", categoryId);
return (int)cmd.ExecuteNonQuery();
}
}
}
Please check have you bind gridview inside
if(!page.ispostback)
{
}
You must update the data to the actual datasource and rebind it.
If you have updated the values then you shall rebind the GridView again with updated values
mGridView.DataSource = {YOUR DATA SOURCE};
mGridView.DataBind();
EDIT 1:
Does this method being called break there check that
have you set update as
commandText ="Update"

how to export data from datagrid to excel without images?

I want to display,insert,update,delete in DataGrid (Asp.net and Sqlserver2008) and then i want to export data from datagrid to excel file.
Table Structure
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>
<!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 id="Head1" runat="server">
<title>'A'</title>
<style type="text`/css">`
.Gridview
{
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
<script type="text/javascript">
function ConfirmationBox(username) {
var result = confirm('Are you sure you want to delete ' + username + ' Details?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server" AutoGenerateColumns="false"
CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" ShowFooter="true" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowDeleting="gvDetails_RowDeleting" OnRowEditing="gvDetails_RowEditing"
OnRowUpdating="gvDetails_RowUpdating"
OnRowCommand="gvDetails_RowCommand" Height="275px" Width="530px">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"
ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server"
ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"
CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server" />
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server" />
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server" />
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
<div>
<asp:Button ID="btn_Excel" runat="server" Text="Excel"
onclick="btn_Excel_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
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.Reflection;
using System.IO;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into Employee_Details(UserName,City,Designation) values('"
+ txtUsrname.Text + "','" + txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
protected void btn_Excel_Click(object sender, EventArgs e)
{
this.gvDetails.AllowPaging = false;
this.gvDetails.AllowSorting = false;
this.gvDetails.EditIndex = -1;
this.BindEmployeeDetails();
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=MyList.xls");
Response.Charset = "";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
gvDetails.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//to Render Control
}
}
My code works fine.
But my excel file looks like this
Excel output
So i don't want the images in datagrid to be exported.
How can i do that.
Kindly reply.
Ok i got the solution (From a colleague).
Please vote my answer if its correct.
Explanation:
1.We have to first make a temporary table.
2.Now add only the required column from datagrid.
3.Use temporary table to Export data in Excel.
Code:In the Button click call the function ExportUsersDataTable
protected void btn_Excel_Click(object sender, EventArgs e){ExportUsersDataTable()}
The function definition is:
public void ExportUsersDataTable()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
string sFilename = "UserToRoleMapping.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = ""; //string.Empty;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFilename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView gvTemp = new GridView();
//Temporary Table for changing the ExcelSheet Headers
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("User Id");
dtTemp.Columns.Add("User Name");
dtTemp.Columns.Add("City");
dtTemp.Columns.Add("Designation");
dtTemp.AcceptChanges();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = dtTemp.NewRow();
dr["User Id"] = ds.Tables[0].Rows[i]["UserId"].ToString();
dr["User Name"] = ds.Tables[0].Rows[i]["UserName"].ToString();
dr["City"] = ds.Tables[0].Rows[i]["City"].ToString();
dr["Designation"] = ds.Tables[0].Rows[i]["Designation"].ToString();
dtTemp.Rows.Add(dr);
dtTemp.AcceptChanges();
}
}
if (dtTemp.Rows.Count > 0)
{
gvTemp.DataSource = dtTemp;
gvTemp.DataBind();
gvTemp.RenderControl(htw);
response.Write(sw.ToString());
}
response.End();
}
}
}

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?

Resources