specific gridview data to be moved into excel file - asp.net

I am trying to move the specific gridview data into the excel file but I am getting an error as object reference not set to the instance of an object
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol0" runat="server" Checked="true"/>
<asp:Label ID="lbl_catid" runat="server" Text=" CategoryID"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_catid" runat="server" Text='<%# Eval("cat_id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol1" runat="server" Checked="true"/>
<asp:Label ID="lbl_catname" runat="server" Text="category Name"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_categoryname" runat="server" Text='<%# Eval("categoryname")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="Chckcol2" runat="server" Checked="true"/>
<asp:Label ID="description" runat="server" Text="description"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_description" runat="server" Text='<%# Eval("description")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my code behind:
public partial class _Default : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("Data Source=localhost;Database=mylibrary_db;User ID=root;Password=MyLuck2010");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}
}
protected void fillgrid()
{
MySqlDataAdapter da = new MySqlDataAdapter("select cat_id,categoryname,description from library_category", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void getcheckedgridview()
{
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
CheckBox chkCol1 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol1");
CheckBox chkCol2 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol2");
ArrayList arr;
if (ViewState["States"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)ViewState["States"];
}
arr.Add(chkCol0.Checked);
arr.Add(chkCol1.Checked);
arr.Add(chkCol2.Checked);
ViewState["States"] = arr;
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
}

The fault is most likely to be with the Convert.ToBoolean(arr[0]); (see the line GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);)
I would put a break tag on the faulting line and see what the value of arr[0] is. I would guess arr is empty or null and your ViewState is not returning the data you are expecting. This maybe because your method getcheckedgridview() is not called by your code (or at least, not by the code you've displayed)!
You could try (where the only change is the first line of the method)
protected void btnExportExcel_Click(object sender, EventArgs e)
{
getcheckedgridview();//Only change to your code
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
ArrayList arr = (ArrayList)ViewState["States"];
GridView1.HeaderRow.Cells[0].Visible = Convert.ToBoolean(arr[0]);
GridView1.HeaderRow.Cells[1].Visible = Convert.ToBoolean(arr[1]);
GridView1.HeaderRow.Cells[2].Visible = Convert.ToBoolean(arr[2]);
GridView1.HeaderRow.Cells[0].FindControl("chkCol0").Visible = false;
GridView1.HeaderRow.Cells[1].FindControl("chkCol1").Visible = false;
GridView1.HeaderRow.Cells[2].FindControl("chkCol2").Visible = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = Convert.ToBoolean(arr[0]);
row.Cells[1].Visible = Convert.ToBoolean(arr[1]);
row.Cells[2].Visible = Convert.ToBoolean(arr[2]);
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
Edit
Based upon your comments, I think the error message is now due to your code not finding the control in question. So
CheckBox chkCol0 = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkCol0");
does not find the control called "chkCol0" and so therefore chkCol0 is null.

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

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

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

bind image from database to datalist

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

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