I want to view the image in gridview from dataBase. In dataBase the image is in byte formate. How to retrieve and view that images in grid View. I don't know how to code for this.Anyone know help me to solve the issue.
To display image in gridview from database.the image is in byte
format.How to view that bytecode as image in gridview
Here is my code:
//Image Upload Code Here//
protected void Add_Click(object sender, EventArgs e)
{
if (!FileUpload1.HasFile)
{
Label2.Visible = true;
Label2.Text = "Please Select Image File"; //checking if file uploader has no file selected
}
else
{
int length = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[length];
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
// SqlCommand cmd1 = new SqlCommand("insert into Student" + "(RegNo,Name,DOB,Gender,Address,Country,Picture) values(#RegNo,#Name,#DOB,#Gender,#Address,#Country,#photo)", con);
SqlCommand cmd1 = new SqlCommand("sp", con);
cmd1.CommandType = CommandType.StoredProcedure;
con.Open();
cmd1.Parameters.AddWithValue("#RegNo", RegNo.Text);
cmd1.Parameters.AddWithValue("#Name", Name.Text);
cmd1.Parameters.AddWithValue("#DOB", Dob.Text);
cmd1.Parameters.AddWithValue("#gender", Gender.SelectedValue);
cmd1.Parameters.AddWithValue("#Address", Address.Text);
cmd1.Parameters.AddWithValue("#Country", Country.Text);
//cmd1.Parameters.AddWithValue("#datetime", DateTime.Now);
cmd1.Parameters.AddWithValue("#Picture", pic);
try
{
cmd1.ExecuteNonQuery();
Label2.Visible = true;
Label2.Text = "Image Uploaded Sucessfully";
con.Close();//after Sucessfully uploaded image
}
catch(Exception ex)
{
throw ex;
}
}
Response.Redirect("~/WebForm1.aspx");
}
}
Actually there is no event with name ItemdataBound for gridview. For gridview use RowDataBound event instead. Below is the sample implementation for the same.
ASPX:
<asp:GridView runat="server" ID="grd" OnRowDataBound ="grd_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<img src='<%# Eval("imagedata") %>' id="imageControl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
System.Web.UI.HtmlControls.HtmlImage imageControl = (System.Web.UI.HtmlControls.HtmlImage)e.Row.FindControl("imageControl");
if (((DataRowView)e.Row.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64," + Convert.ToBase64String((byte[])(((DataRowView)e.Row.DataItem))["imagedata"]);
}
}
}
You can use ItemDataBound event of grid view as given below:
if(e.Item.ItemType ==ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.HtmlControls.HtmlImage imageControl =(System.Web.UI.HtmlControls.HtmlImage) e.Item.FindControl("imageControl");
if (((DataRowView)e.Item.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
}
}
First find the image control inside your grive view and set it's image source property to "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
Note: imagedata should be the name of column you used to save image.
Related
I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
I have the following code (asp.net and code-behind) that achieves the sort:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PullData("", "");
ViewState["sortOrder"] = "";
}
}
public void PullData(string sortExp, string sortDir)
{
DataTable taskData = new DataTable();
string connString = #"user id = dsfsdfds;" + "password= sadasdada; server= mg; database= ob;" /*+ "Trusted_Connection=yes;"*/ + "connection timeout=30";
string query = #"SELECT 'http://mg/appnet/workview/objectPop.aspx?objectid=' + CAST(CT.OBJECTID AS VARCHAR) + '&classid=1224' 'Task Detail'
,UG.USERGROUPNAME 'Services'
,CT.ATTR2812 'Status'
,CT.ATTR2752 'Due Date'
,CT.ATTR2739 'Task Name'
FROM dbo.RMOBJECTINSTANCE1224 CT
WHERE CT.ACTIVESTATUS = 0";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(query, conn);
// this will query your database and return the result to your datatable
DataSet myDataSet = new DataSet();
da.Fill(myDataSet);
DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;
if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
yourTasksGV.DataSource = myDataView;
yourTasksGV.DataBind();
conn.Close();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
protected void yourTasksGV_Sorting(object server, GridViewSortEventArgs e)
{
PullData(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "Desc")
{
ViewState["sortOrder"] = "Asc";
}
else
{
ViewState["sortOrder"] = "Desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
My GridView:
<asp:GridView AlternatingRowStyle-BackColor="#E2E2E2" AutoGenerateColumns="false" OnSorting="yourTasksGV_Sorting" AllowSorting="true" ID="yourTasksGV" runat="server" ClientIDMode="Static" EmptyDataText="There is no data to display" OnRowDataBound="yourTasksGV_RowDataBound" OnRowCreated="yourTasksGV_RowCreated">
<Columns>
<asp:HyperLinkField Target="_blank" DataNavigateUrlFields="Task Detail" DataTextField="Task Name" DataNavigateUrlFormatString="" HeaderText="Task Details" SortExpression="Task Detail" ItemStyle-Width="35%" ItemStyle-CssClass="taskTableColumn" />
<asp:BoundField DataField="Services" HeaderText="Services" SortExpression="Services" ItemStyle-Width="25%" ItemStyle-CssClass="taskTableColumn" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" ItemStyle-Width="15%" ItemStyle-CssClass="taskTableColumn" />
<asp:BoundField DataField="Due Date" HeaderText="Due Date" SortExpression="Due Date" ItemStyle-Width="15%" ItemStyle-CssClass="taskTableColumn" />
</Columns>
</asp:GridView>
For the first column I am taking the Task Name and showing as the display text for the link in Task Detail column from the SQL query (DataTextField is Task Name instead of Task Details).
How can I modify my code to do the following:
When I click on the Task Details tab it should sort by the Task Name that is shown as the display for the link which is the Task Detail?
Display an image next to the header text which I am sorting the table by? (up.png and down.png)?
On page load, sort by #1 ASC and display the image respectively?
My GridView that is being shown to the user (Note how the first column the link is used inside the href and the display text is the Task Name):
there is an useful solution here :
http://blogs.msdn.com/b/scothu/archive/2010/08/28/gridview-with-sort-arrows-and-showing-header-when-empty.aspx
and you can do this
to display image use this code:
protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Call the GetSortColumnIndex helper method to determine
//the index of the column being sorted.
int sortColumnIndex = GetSortColumnIndex();
if (sortColumnIndex != -1)
{
// Call the AddSortImage helper method to add
// a sort direction image to the appropriate
// column header.
AddSortImage(sortColumnIndex, e.Row);
}
}
}
int GetSortColumnIndex()
{
// Iterate through the Columns collection to determine the index
// of the column being sorted.
foreach (DataControlField field in gv.Columns)
{
if (field.SortExpression == gv.SortExpression)
{
return gv.Columns.IndexOf(field);
}
}
return -1;
}
void AddSortImage(GridViewRow headerRow)
{
int iCol = GetSortColumnIndex();
if (-1 == iCol)
return;
// Create the sorting image based on the sort direction.
Image sortImage = new Image();
if (SortDirection.Ascending == this.GridView1.SortDirection)
{ sortImage.ImageUrl = #"~\Images\BlackDownArrow.gif";
sortImage.AlternateText = "Ascending Order";
} else
{
sortImage.ImageUrl = #"~\Images\BlackUpArrow.gif";
sortImage.AlternateText = "Descending Order";
}
// Add the image to the appropriate header cell.
headerRow.Cells[iCol].Controls.Add(new LiteralControl(" "));
headerRow.Cells[iCol].Controls.Add(sortImage);
}
and to sort, enable gridview "allowsorting property" and add `Sort Expression" to the columns properties.
I have written a code which checks unique ID availability status.. if ID is available it should make panel visible otherwise the panel visibility is hidden. But it is not working. If i set panel visibility to false in page load it works.. but panel visibility code inside text change event of textbox, doesnt work. In my view page script manager is present to update content inside update panel. What am i doing wrong.
<asp:ScriptManager ID="scriptmanager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="PnlUsrDetails" runat="server">
<ContentTemplate>
<table>
<tr>
Enter unique no: <asp:TextBox ID="txtUniqueNo" runat="server" AutoPostBack="true" ontextchanged="txtUniqueNo_TextChanged"/>
</tr>
<tr>
<div id="checkusername" runat="server" Visible="false">
<asp:Image ID="imgstatus" runat="server" Width="17px" Height="17px"/>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="Panel1" runat="server">
<div>Panel content</div>
</asp:Panel>
server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
Panel1.Visible = false;
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Visible = false;
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Visible = true;
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
My file upload is also in update panel,, which loses its file on upload. Suggest me any alternative approaches to achieve this functionality...
Thanks
Problably cause the Control is not rendered (visible=false) and no viewstate is saved before.
Try to hide and show it with styles:
First:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
//Panel1.Visible = false; Comment
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Style.Add("display", "none");
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Style.Add("display", "block");
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
File upload control will not work inside Update panel in this case it will lose selected file for sure.Since you have asked for alternative approach.One way is to check unique no availablity using jquery. Here is the perfect working link Check-UserName-Availability-jquery to check username availability. use this example to check unique no.
Ajax has success and error methods, so you can place your form inside a div with unique id and toggle its visibility on ajax result.
Upoo the success of ajax you can show your div in which form is present. This will eliminate the need to use script manager and update panel.
I am creating a c# application.
In this application I take inputs from user and using those entries I fire a sql query and dispay the results in the Gridview.
So these actions happen when we click on submit button.
After this, I want to give the user an option to export the gridview results to an excel sheet by clicking on another submit button.
the code for these things is:
aspx code:
<body>
<form id="form1" runat="server">
<div>
<b>Enter Value 1 :</b>
<asp:TextBox ID="p1" runat="server" />
<br />
<b>Enter value 2 :</b>
<asp:TextBox ID="p2" runat="server" /><br />
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="Start Search" />
<asp:Button ID="btn2" runat="server" OnClick="Button2_Click" Text="Export Data to Excel" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
OnPageIndexChanging="gridView_PageIndexChanging"
ShowFooter="false"
CssClass="gridstyle"
EnableViewState="false"
AllowPaging="true">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" />
<RowStyle Wrap="false" />
<HeaderStyle Wrap="false" />
</asp:GridView>
</div>
</form>
</body>
The code file for this code is:
public partial class pSearch : System.Web.UI.Page
{
SqlConnection sqlconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
DataSet dsldata;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds0 = new DataSet();
ds0 = (DataSet)Session["data"];
DataView dataview_ldata = dsldata.Tables[0].DefaultView;
DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dataview_ldata;
GridView1.DataBind();
ExportToExcel(GridView1);
}
private void ExportToExcel(GridView GrdView)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GrdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string RName = Page.Request.QueryString["RName"];
string typeofquery = "mycommand";
string pv1 = p1.Text ;
string pv2 = p2.Text ;
string abc = null;
abc = "" + typeofquery + " #RName=" + RName + ",#P1='" + pv1 + "',#P2='" + pv2 + "'";
SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
GridView1.PageSize = 1000;
cmdldata.SelectCommand.CommandTimeout = 600;
dsldata = new DataSet();
ErrorHandling errhandle = new ErrorHandling();
try
{
cmdldata.Fill(dsldata);
Session["data"] = dsldata;
DataView dataview_ldata = dsldata.Tables[0].DefaultView;
DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dataview_ldata;
GridView1.DataBind();
}//end of try
catch (Exception ex)
{
String errorMessage = errhandle.displayException(ex);
Response.Write(errorMessage);
}//end of catch
finally
{
if (errhandle != null)
{
errhandle = null;
}
}//end of finally
}
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
}
I am getting an empty excel sheet right now as my output.
From my anaysis I think the following is the problem:
When button 1 is clicked Gridview is generated by the query.When button 2 is clicked , all the data that It had previously is lost (even though we can still see it on the screen).That is why I am getting an empty excel sheet right now.
Secondly,Since I am creating the gridview on button click and not on the page load,the data of the gridview is not available in the
protected void Button2_Click(object sender, EventArgs e){}
function.
Only option now to make it working is I should do the same operations of executing the query again on button2_Click function also.
But again I don't think this is an efficient way.And moreover I am running a complex query that may take 3 -4 mins at times to give the output.So running the query two times is out of question. I also tried caching the dataset but it did not work.Even creating session in not working.
I have been breaking my head on this since last 1 day. Please help me! Thank you.
Cache sounds like a good solution, could you post your cache code?
Otherwise, I would do it in ViewState. Get the result of your long query, store it in ViewState, bind the result to the GridView, then after your button click, you can access the ViewState-stored data. This isn't the best way to do it for large sets of data, because ViewState is sent across the wire with each PostBack and stored on the client side. It can really slow your application down and cause unexpected errors.
Here's my edit, that I got working locally:
Storing it in Session should work fine. Here's what I did with some dummy data. FYI, you can bind a GridView directly to a DataSet, you don't have to drill down to a DataTable or anything like that.
protected void Button1_Click(object sender, EventArgs e)
{
string RName = Page.Request.QueryString["RName"];
string typeofquery = "mycommand";
string pv1 = p1.Text;
string pv2 = p2.Text;
string abc = null;
abc = "" + typeofquery + " #RName=" + RName + ",#P1='" + pv1 + "',#P2='" + pv2 + "'";
SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
GridView1.PageSize = 1000;
cmdldata.SelectCommand.CommandTimeout = 600;
var dummyDt = new DataTable();
dummyDt.Columns.Add("Sup");
dummyDt.Columns.Add("Bro");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dsldata = new DataSet();
dsldata.Tables.Add(dummyDt);
//ErrorHandling errhandle = new ErrorHandling();
try
{
//cmdldata.Fill(dsldata);
Session["data"] = dsldata;
//DataView dataview_ldata = dsldata.Tables[0].DefaultView;
//DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dsldata;
GridView1.DataBind();
}//end of try
catch (Exception ex)
{
//String errorMessage = errhandle.displayException(ex);
Response.Write(ex.Message);
}//end of catch
finally
{
//if (errhandle != null)
//{
// errhandle = null;
//}
}//end of finally
}
protected void Button2_Click(object sender, EventArgs e)
{
//DataSet ds0 = new DataSet();
//ds0 = ;
//DataView dataview_ldata = dsldata.Tables[0].DefaultView;
//DataTable dt = dsldata.Tables[0];
GridView1.DataSource = (DataSet)Session["data"];
GridView1.DataBind();
ExportToExcel(GridView1);
}
private void ExportToExcel(GridView GrdView)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GrdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}