How to add new row in a gridview on button click - asp.net

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();
}
}
}

Related

How can I make Excel like grid in asp.net C# Webform

How can I make a grid like in Excel in ASP.NET WebForms?
I would like rows and columns where user can enter data and after a click on a save button the data would be inserted into a database.
Hope this will help you out to full-fill your requirement.Here I am giving only aspx and c# coding. Create and modify your database and change the code accordingly.Here I am using direct insert statement you can use stored procedure.
Table in Database:-
page.aspx :-
<asp:GridView ID="excelgrd" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:BoundField DataField="Slno" HeaderText="SL No" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txnm" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txdesc" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="svbtn" runat="server" Text="Save" OnClick="svbtn_Click" />`
code behind of your page :-
`
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
bindgrd();//bind your grid
}
}
private void bindgrd()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Slno", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Desc", typeof(string)));
dr = dt.NewRow();
dr["Slno"] = 1;
dr["Name"] = string.Empty;
dr["Desc"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
excelgrd.DataSource = dt;
excelgrd.DataBind();
}
protected void addnewrow()
{
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++)
{
//extract the TextBox values
TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["Slno"] = i + 1;
dtCurrentTable.Rows[i - 1]["Name"] = tx1.Text;
dtCurrentTable.Rows[i - 1]["Desc"] = tx2.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
excelgrd.DataSource = dtCurrentTable;
excelgrd.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox tx1 = (TextBox)excelgrd.Rows[rowIndex].Cells[1].FindControl("txnm");
TextBox tx2 = (TextBox)excelgrd.Rows[rowIndex].Cells[2].FindControl("txdesc");
tx1.Text = dt.Rows[i]["Name"].ToString();
tx2.Text = dt.Rows[i]["Desc"].ToString();
rowIndex++;
}
}
}
}
protected void svbtn_Click(object sender, EventArgs e)
{
foreach(GridViewRow r in excelgrd.Rows)
{
string des =(r.FindControl("txdesc") as TextBox).Text;
string nm = (r.FindControl("txnm") as TextBox).Text;
try
{
con.Open();
SqlCommand sql = new SqlCommand("insert into test (name,name_desc) values('"+nm+"','"+des+"')", con);
sql.ExecuteNonQuery();
sql.Dispose();
}
catch (Exception e1)
{
string error = e1.ToString();
}
finally
{
con.Close();
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
addnewrow();
}`

Unchecking Selected Date in Calendar

I have a asp calendar utility in ascx page. I want to unselect the selected date on second click on the same date. The following are my codes. Kindly help in this.
<%# Control Language="C#" AutoEventWireup="true"CodeFile="Calendar.ascx.cs"Inherits="WebUserControl" %>
<table>
<tr>
<td width="100%">
<asp:DropDownList ID="ddlyear" runat="server"
onselectedindexchanged="ddlyear_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="2014" Value="2014" Selected="True"></asp:ListItem>
<asp:ListItem Text="2015" Value="2015"></asp:ListItem>
<asp:ListItem Text="2016" Value="2016"></asp:ListItem>
<asp:ListItem Text="2017" Value="2017"></asp:ListItem>
<asp:ListItem Text="2018" Value="2018"></asp:ListItem>
<asp:ListItem Text="2019" Value="2019"></asp:ListItem>
<asp:ListItem Text="2020" Value="2020"></asp:ListItem>
<asp:ListItem Text="2021" Value="2021"></asp:ListItem>
<asp:ListItem Text="2022" Value="2022"></asp:ListItem>
<asp:ListItem Text="2023" Value="2023"></asp:ListItem>
<asp:ListItem Text="2024" Value="2024"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="100%" dir="ltr">
<asp:DataList ID="DataList1" runat="server" HorizontalAlign="Center"
RepeatDirection="Horizontal" RepeatColumns="4"
onitemdatabound="DataList1_ItemDataBound"
>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txt1" runat="server" Text='<%#Eval("Month") %>' Visible="false" Font-Names="Arial"></asp:Label>
<asp:HiddenField ID="hdn1" runat="server" />
<asp:Calendar ID="Calendar1" runat="server" NextPrevFormat="CustomText" SelectionMode="Day" NextMonthText="" PrevMonthText="" Font-Names="A" OtherMonthDayStyle-BorderStyle="NotSet" OtherMonthDayStyle-Wrap="False" OtherMonthDayStyle-ForeColor="#CCCCCC">
<TitleStyle
BackColor="#6EC347"
ForeColor="White"
Height="36"
Font-Size="Large"
Font-Names="Arial"
/>
<SelectedDayStyle
BackColor="Green"
BorderColor="SpringGreen"
/>
</asp:Calendar>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
My code behind for this ascx page is
public partial class WebUserControl : System.Web.UI.UserControl
{
int month = 1;
public event EventHandler YearChanged;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadcalendar();
}
}
private void loadcalendar()
{
DataTable dt = new DataTable();
dt.Columns.Add("Month", typeof(string));
dt.Rows.Add("January");
dt.Rows.Add("February");
dt.Rows.Add("March");
dt.Rows.Add("April");
dt.Rows.Add("May");
dt.Rows.Add("June");
dt.Rows.Add("July");
dt.Rows.Add("August");
dt.Rows.Add("September");
dt.Rows.Add("October");
dt.Rows.Add("Novemeber");
dt.Rows.Add("December");
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
string year = ddlyear.SelectedValue.ToString();
String str = ((Label)e.Item.FindControl("txt1")).Text;
DateTime Now = DateTime.Now;
DateTime TempDate = new DateTime(Convert.ToInt32(year), month, 1);
// DateTime TempDate = new DateTime(Now.Year,Now.Month, 1);
((Calendar)e.Item.FindControl("Calendar1")).VisibleDate = TempDate;
month = month + 1;
}
}
protected void ddlyear_SelectedIndexChanged(object sender, EventArgs e)
{
loadcalendar();
YearChanged(sender, e);
}
}
My Aspx.cs page code is like this
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
string eid;
string ename = DropDownList2.SelectedValue.ToString();
if (ename == "1")
{
eid = "1";
}
else
{
eid = "2";
}
int cid = Int32.Parse(DropDownList1.SelectedValue.ToString());
//String sqlSelect = String.Format("Select Customer_Id from Customer where Customer_Name='{0}'", cname);
//SqlCommand cmd1 = new SqlCommand(sqlSelect, cnn);
//int cid = (int)cmd1.ExecuteScalar();
DataList dl;
dl = ((DataList)patchCalendar.FindControl("DataList1"));
foreach (DataListItem dli in dl.Items)
{
string month = Convert.ToString(((Label)dli.FindControl("txt1")).Text);
string day = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Day);
string year = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Year);
string date = ((Calendar)dli.FindControl("Calendar1")).SelectedDate.ToShortDateString();
if (date == "1/1/0001")
{
year = null;
date = null;
day = null;
}
else
{
SqlCommand cmd = new SqlCommand("insert into Patching_Dates values(#cid,#eid,#year,#month,#day,#date)", cnn);
cmd.Parameters.AddWithValue("#cid", cid);
cmd.Parameters.AddWithValue("#eid", eid);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#day", day);
cmd.Parameters.AddWithValue("#date", date);
cmd.ExecuteNonQuery();
}
}
cnn.Close();
string act = "Patching Dates Added";
cnn.Open();
SqlCommand cmd2 = new SqlCommand("insert into Logs values(#Username,#Activity,#Time)", cnn);
cmd2.Parameters.AddWithValue("#Username", (string)(Session["user"]));
cmd2.Parameters.AddWithValue("#Activity", act);
cmd2.Parameters.AddWithValue("#Time", System.DateTime.Now.ToString());
cmd2.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
First check Calendar1 control having value if yes then reset it by this
Calendar1.SelectedDates.Clear();

checkbox_oncheckedchange event not firing in a gridview

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

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();
}
}
}

Resources