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.
Related
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.
I'm stuck with a problem where i can't get the values of any control not just textboxes in button click event so here is the scenario, You can skip it and just can look into my button click event
Page product is performing 2 operations
Create
Update
When a user clicks Edit on GridView in updpage It will redirects it to Product Page to update, Same page is performing Create product operation too, So when I receive QueryString value I'll update the product table and when I won't so I just perform Create operation.
Now I'm stuck when there is no QueryString value so textboxes are updating with a new values but when there is, so they don't give me a new value.
Here is my code
On pageLoad Event I'm filling text boxes with there respective values
where there is an update operation
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
}
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Button event code
protected void btn_Insert_Click(object sender, EventArgs e)
{
getpicture();
SqlCommand cmd;
string pathimage ="";
if (pathimage == "")
{
pathimage = product_image.ImageUrl;
}
else
{
pathimage = ViewState["pathimage"].ToString();
}
if (Request.QueryString["update"] != null)
{
int id = int.Parse(Request.QueryString["update"]);
string query = "UPDATE Products SET product_name=#PRODUCTNAME,price=#PRIZE,unit=#UNIT,product_image=#IMAGE,available=#AVAILABLE,product_category=#CATEGORY,product_brand=#BRAND,product_achv=#ACHIV WHERE id = #ID";
cmd = new SqlCommand(query);
txt_name.Text = "";
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
cmd.Parameters.Add("#ID", id);
param.InsertUpdateData(cmd);
}
else
{
string query = "INSERT INTO Products(product_name,price,unit,product_image,available,product_category,product_brand,product_achv) VALUES(#PRODUCTNAME,#PRIZE,#UNIT,#IMAGE,#AVAILABLE,#CATEGORY,#BRAND,#ACHIV)";
cmd = new SqlCommand(query);
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
param.InsertUpdateData(cmd);
}
}
It is getpicture function used in btn_submit
private void getpicture()
{
try
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string root = Server.MapPath("~");
string path = root + "assets\\images\\products\\";
FileUpload1.SaveAs(path + FileName);
ViewState["pathimage"] = "/assets/images/products/" + FileName;
this.product_image.ImageUrl = "../assets/images/products/upload.png";
}
else
{
Response.Write("Select an Image");
}
}
catch (Exception ex)
{
Response.Write("Select an Image");
}
}
Providing Data access layer Insert Update Data code too
public Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OnlineStoreConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
System.Web.HttpContext.Current.Response.Write("Succed");
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.ToString());
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Server Controls
<div class="row">
<div class="col-md-6">
<asp:TextBox ID="txt_name" runat="server" CssClass="form-control" placeholder="Product Name"></asp:TextBox>
<br />
<asp:TextBox ID="txt_price" runat="server" CssClass="form-control" placeholder="Product Price"></asp:TextBox>
<br />
<asp:TextBox ID="txt_unit" runat="server" CssClass="form-control" placeholder="Product Unit"></asp:TextBox>
<br />
<asp:DropDownList ID="dd_available" runat="server" CssClass="form-control">
<asp:ListItem>Is Product Available</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Not Avaliable</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="dd_category" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_brand" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_achievment" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
</div>
<div class="col-md-2"></div>
<div class="col-md-4">
<asp:Image ID="product_image" runat="server" style="height:231px;width:225px;" CssClass="form-control" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange = "show_image(this);" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3 col-md-offset-6">
<asp:Button ID="btn_Insert" runat="server" Text="Create Product" CssClass="btn btn-primary btn-lg" OnClick="btn_Insert_Click" />
</div>
</div>
Before Clicking update button
Before clicking update button
After I updated text box values respectively and when click button Upload None of my server control value changes. Here it is
Watching local variable
But in case of Creating Product it works
Saad, i think the error is in the page_load event. If in your querystring the update param is not null, then you are always replacing the textboxes with the data of your DB.
Your code should be like this
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Hope it helps...
I have a code like this
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Visible="False" Text="Please update the price"></asp:Label>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
and C# is
namespace WebApplication6
{
public partial class WebForm20 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["onealbumid"] != null)
{
Label1.Visible = true;
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
SqlCommand cmd = new SqlCommand("Select Price from OneAlbum where OneALbumID='" + onealbumid + "'", con);
con.Open();
TextBox1.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
else {
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
SqlCommand command = new SqlCommand(#"UPDATE [dbo].[OneAlbum]
SET Price=#Price where OneAlbumID =" + onealbumid + ";", con);
command.Parameters.AddWithValue("#Price", TextBox1.Text);
con.Open();
command.ExecuteNonQuery();
con.Close();
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
}
There is a page/form, before this page, users select the price which users want to change from the gridview
I want users to edit new "Price" in the textbox1 on this page.
So this is happening right now.
For example, I choose "Price" 22 before this page and when this page opens/loads textbox1 showing 22.
so I change/type to 40 in Texbox1, and click button.
The price is still 22. not 40 and I checked the database, which still did not change, still 22
why is this happening?
The Page_Load will overwrite the data you are entering. Put a !IsPostBack check around that so that when you do click the button the data isn't being put back to what it was when the form loaded.
Also, where is a gridview in this code? There is such a class and thus beware of what terms you use given the code you show.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am not able to recognize what I am doing wrong in my code. Can someone help ? I want to delete all the images which are checked using c# .
my code snippet looks like this :-
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "errror";
}
}
.aspx page contains :-
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
Thanks in advance :)
Here are some pointers:
The names you use are difficult to understand in your codebehind. You now have 1 repeater but in case you have multiple it is better to use a more specific name.
Depending on the .NET version you can use generic types to declare your variables.
SqlCommand cmd = new SqlCommand(str, con);
becomes:
var sqlCommand = new SqlCommand(queryString, connectionString);
Your not closing the connection. If your in newer versions of .NET the best approach would in my opinion be:
private string ConnectionString = webConfigurationManager.ConnectionStrings["connectionstring"] != null ? WebConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString : "";
if (!string.IsNullOrEmpty(this.ConnectionString))
{
using (var sqlConnection = new SqlConnection(this.ConnectionString))
{
//your code here
}
}
You are catching an error but your not doing anything with the provided information.
use:
Catch (Exception exception)
{
ErrorLabel.Text = string.format("The following error has occurred: {0}.", exception.Message);
}
to use the exception.Message where desired.
In modern implementations you are most probably better off using an MVC application using EntityFramework and MVC Razor.
Defining your SQL queries like that is dangerous also. If I edit the post value of the literal to something like "ID AND 1 = 1" I will now delete all photos.
Here are some pages to help you get started with Entityframework and MVC:
http://www.asp.net/mvc/tutorials
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
I will give you some good pointers in improvements in a minute. First try this and change the literal value to the column you use as an id in case I got it wrong:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1")
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
if (CheckBox1 != null && litMessageId != null && CheckBox1.Checked)
{
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "error";
}
}
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>");
}
}