How can I display image in gridview with 3 tier architecture? - c#

For data access layer:
Source:
public string insert_details(bisuness_object user_details)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_rgsthome values(#firstname,#lastname,#emailid,#password,#address,#upload)", con);
try
{
cmd.Parameters.AddWithValue("#firstname", user_details.firstname_value);
cmd.Parameters.AddWithValue("#lastname", user_details.lastname_value);
cmd.Parameters.AddWithValue("#emailid", user_details.emailid_value);
cmd.Parameters.AddWithValue("#password", user_details.pass_value);
cmd.Parameters.AddWithValue("#address", user_details.addr_value);
cmd.Parameters.AddWithValue("#upload", user_details.fileupl_value);
//cmd.Parameters.AddWithValue("#imagepath", user_details.imgpth_value);
return cmd.ExecuteNonQuery().ToString();
}
catch (Exception show_error)
{
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
home.aspx:
public string getimage(object ob)
{
string img = #"/image/" + ob.ToString();
return img;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
bisuness_object bo = new bisuness_object();
// cmd.Parameters.AddWithValue("#imagepath", ("#uploadimage") + filename);
bo.firstname_value = TextBox1.Text;
bo.lastname_value = TextBox2.Text;
bo.emailid_value = TextBox3.Text;
bo.pass_value = TextBox4.Text;
bo.addr_value = TextBox6.Text;
bo.fileupl_value = FileUpload1.FileName.ToString();
bisuness_layer bl = new bisuness_layer();
bind();
try
{
string result = bl.record_insert(bo);
}
catch (Exception info)
{
throw info;
}
finally
{
bo = null;
bl = null;
bind();
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
how to solve it.....please help me
i want to image in gridview

bind the image tag inside the gridview dynamically
by giving the path dynamically
<asp:Image ID="image" Style="width:100px; height:100px;" runat="server" ImageUrl='<%# "~/folder/subfolder/" + Eval("id") +"."+ Eval("imagetype") %>' />
and the method for binding the gridview
protected void GetDayoffer()
{
gridview1.DataSource = bl.method();
gridview1.DataBind();
}
hope this will help you or recovert the bytes into image again and bind it into gridview

Related

update image didn't display in gridview in c#

I have been created student details form by using aspx and c#.
In the image field i got some error.
What i have done:
Insert,edit and update image.
When i insert image and submit, I was set to display that image in gridview on the same page, and also save in "images" folder in my drive.
It works fine, but when i edit the image and upload new image and submit, the changed image didn't show in the gridview, but this changed image saved in "images" folder.
May i know, what is my mistake in my code?
Here is my source code:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("sp_updatestudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = Image1.ImageUrl.Substring(Image1.ImageUrl.IndexOf('/')+1);
string[] files = Directory.GetFiles(Server.MapPath("~/Images"));
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
foreach (string f in files) File.Delete(f);
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + filename : (uniqueFileName.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
else
{
SqlCommand com = new SqlCommand("sp_insertstudentdetail", con);
com.CommandType = CommandType.StoredProcedure;
try
{
string filename = string.Empty;
string uniqueFileName = string.Empty;
if (fileupload.PostedFile.FileName.Length > 0)
{
filename = Path.GetFileName(fileupload.PostedFile.FileName);
string fileExtension = Path.GetExtension(filename).ToLower();
uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
fileupload.SaveAs(Server.MapPath("~/Images/" + uniqueFileName));
}
com.Parameters.AddWithValue("#Image", (filename.Length > 0) ? "Images/" + uniqueFileName : string.Empty);
com.ExecuteNonQuery();
}
catch (Exception ex)
{
btnsub.Text = ex.Message;
}
}
}
Here is editrow:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
Image1.ImageUrl = ((System.Web.UI.WebControls.Image)gr.Cells[7].Controls[0]).ImageUrl;
}
}
and here is my output of my screenshot:
http://s3.postimg.org/bpgzjlmub/untitled.jpg
Can anyone help me to fix my issue, I'm new to .net.
Any help would be highly appreciated.
The gridview in asp.net does not automatically update itself. You need to again bind the gridview. What you need to do is put the code of binding the grid in one function say bindgrid() something like this.
public void bindgrid()
{
con = new SqlConnection(connStr);
con.Open();
da = new SqlDataAdapter("select * from Grid_Data", con);
Dataset ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and then call bindgrid() after every insert and update performed in grid. If this doesn't work out, I might need to see your binding logic.
Thank you

code asp.net c# oledb, cookies, if else

Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.

Exporting data to excel

the code works to a certain extent when I export the data to excel it works fine but if I go back into the application and add, delete or update any of the datagrid when I export the data again it doesn't export the changes. I have deleted the original csv file in case it was an overwriting problem but still get the same problem.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class FormAccounts : Form
{
String constring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Accounts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
//String cmdselect = #"select * Accounts";
String cmdupdate = #"update Accounts set date = #date, moneyin = #moneyin, retailin = #retailin, rent = #rent, stock = #stock, transport = #transport, misc = #misc, bills = #bills, comments = #comments where ID = #id";
String cmdinsert = #"insert into Accounts (date, moneyin, retailin, rent, stock, transport, misc, bills, comments) values (#date, #moneyin, #retailin, #rent, #stock, #transport, #misc, #bills, #comments )";
String cmddelete = #"delete from Accounts where ID =#ID";
public FormAccounts()
{
InitializeComponent();
}
private void FormAccounts_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'accountsDataSet.Accounts' table. You can move, or remove it, as needed.
this.accountsTableAdapter.Fill(this.accountsDataSet.Accounts);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdinsert, con);
try
{
da.InsertCommand.Parameters.Add("#date", SqlDbType.Date);
da.InsertCommand.Parameters["#date"].Value = dtpaccs.Value;
da.InsertCommand.Parameters.Add("#moneyin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#moneyin"].Value = textmoneyin.Text ;
da.InsertCommand.Parameters.Add("#retailin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#retailin"].Value = textretailin.Text;
da.InsertCommand.Parameters.Add("#rent", SqlDbType.Decimal);
da.InsertCommand.Parameters["#rent"].Value = textrent.Text;
da.InsertCommand.Parameters.Add("#stock", SqlDbType.Decimal);
da.InsertCommand.Parameters["#stock"].Value = textstock.Text;
da.InsertCommand.Parameters.Add("#transport", SqlDbType.Decimal);
da.InsertCommand.Parameters["#transport"].Value = texttransport.Text;
da.InsertCommand.Parameters.Add("#misc", SqlDbType.Decimal);
da.InsertCommand.Parameters["#misc"].Value = textmisc.Text;
da.InsertCommand.Parameters.Add("#bills", SqlDbType.Decimal);
da.InsertCommand.Parameters["#bills"].Value = textbills.Text;
da.InsertCommand.Parameters.Add("#comments", SqlDbType.VarChar);
da.InsertCommand.Parameters["#comments"].Value = textcomments.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
cleartexts();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string date = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
lbldate.Text = date;
lblID.Text = id;
dtpaccs.Value = Convert.ToDateTime(date);
textmoneyin.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textretailin.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textrent.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textstock.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
texttransport.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
textmisc.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
textbills.Text = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
textcomments.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(cmdupdate, con);
try
{
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = lblID.Text;
da.UpdateCommand.Parameters.Add("#date", SqlDbType.Date).Value = lbldate.Text;
da.UpdateCommand.Parameters.Add("#moneyin", SqlDbType.Decimal).Value = textmoneyin.Text;
da.UpdateCommand.Parameters.Add("#retailin", SqlDbType.Decimal).Value = textretailin.Text;
da.UpdateCommand.Parameters.Add("#rent", SqlDbType.Decimal).Value = textrent.Text;
da.UpdateCommand.Parameters.Add("#stock", SqlDbType.Decimal).Value = textstock.Text;
da.UpdateCommand.Parameters.Add("#transport", SqlDbType.Decimal).Value = texttransport.Text;
da.UpdateCommand.Parameters.Add("#misc", SqlDbType.Decimal).Value = textmisc.Text;
da.UpdateCommand.Parameters.Add("#bills", SqlDbType.Decimal).Value = textbills.Text;
da.UpdateCommand.Parameters.Add("#comments", SqlDbType.VarChar).Value = textcomments.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Accounts Updated");
con.Close();
cleartexts();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
var rindex = dataGridView1.SelectedCells[0].RowIndex;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand(cmddelete, con);
try
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to delete this record", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
da.DeleteCommand.Parameters.Add("#ID", SqlDbType.Int).Value = accountsDataSet.Accounts[rindex].ID;
con.Open();
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
con.Close();
cleartexts();
}
else
{
MessageBox.Show("Delete Cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cleartexts()
{
//Clears textboxes
textmoneyin.Text = "";
textretailin.Text ="";
textrent.Text = "";
textstock.Text = "";
texttransport.Text = "";
textmisc.Text = "";
textbills.Text = "";
textcomments.Text = "";
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
int cols;
string directory = #"C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Excel Exports";
string filename = string.Format("{0:dd-MM-yy}__{1}.csv", DateTime.Now, "Accounts");
string path = Path.Combine(directory, filename);
//open file
using (StreamWriter wr = File.CreateText(path))
{
//determine the number of cols and write to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Operation Complete " +path);
}
}
}
}
Found the problem. The application needs to be shut down and restarted for the new data to copy over. Is there a way to do that once the datagrid has been changed / updated?

Getting updated value of Textbox in asp.net and c#

I am searching and posting a lot in this issue,but could not get the satisfactory answer.I wanted to make sure that whenever I am making a call to server the value of Textbox should be the one which is the most updated one.
But when I am making the call to server the old value of the textbox persists.I know it is something to do with the postback,but I am not getting the exact way to get the updated value of textbox in my .cs file.
Please tell me what are the necessary steps that I should take to always get the latest value of the textbox.
Here is my code which is not working:
protected void Page_Load(object sender, EventArgs e)
{
int contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside not PostBack";
}
else
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" +TextBox1.Text + "' where contentID= '"+contentID +"'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Here is my aspx page code:
<asp:TextBox ID="TextBox1" runat="server" Height="500px"
TextMode="MultiLine" Width="90%" AutoPostBack="True"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Delete post" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Save changes" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</p>
Please also tell me the reason why it is not working and how I can make it work.
Thanks,
Amandeep
According to the ASP.NET's life cycle, Page_Load executes before Button2_Click, so you have to show your updated text in the Button2_Click:
protected void Page_Load(object sender, EventArgs e)
{
contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "Inside not PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" + TextBox1.Text + "' where contentID= '" + contentID + "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}

Save button click event getting fired up on refreshing the page once done with binding the data to a gridview through save button in asp.net

I am working on a web application using C# and ASP.NET. I am binding the data to the gridview through the textboxes in the same page and I wrote the binding method in my "Save" button click event.
Now, it's really strange thing to find that the grid view is getting bound again with duplicate rows once I refresh the page up on saving the data to the gridview from textboxes through "save" button_click event. I have tried loading the page on firefox, chrome and IE 8....but the result is negative....
Could anyone let me know why is it happening and guide me to resolve it....
This is my C# code:
string con = ConfigurationSettings.AppSettings["ConnectionStrings"];
protected void Page_Load(object sender, EventArgs e)
{
tbladdasset.Visible = false;
btnsaveasset.Enabled = false;
lblErrMsg.Text = "";
if (!IsPostBack)
{
bindassets("", "");
ViewState["sortOrder"] = "";
}
}
private void bindassets(string sortExp, string sortDir)
{
try
{
SqlConnection con1 = new SqlConnection(con);
con1.Open();
SqlCommand cmd = new SqlCommand("select Description,CONVERT(VARCHAR(10), RecievedDate, 101) as DateRecieved,cost,Modelno,Quantity from Asset", con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con1.Close();
if (dt.Rows.Count > 0)
{
DataView dv = dt.DefaultView;
if (sortExp != string.Empty)
{
dv.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
grdvAssets.DataSource = dv;
grdvAssets.DataBind();
}
else
{
lblErrMsg.Text = "No data found...";
}
btnsaveasset.Enabled = false;
tbladdasset.Visible = false;
}
catch
{
lblErrMsg.Text = "Failed to connect server...";
}
}
protected void btnaddnew_Click(object sender, EventArgs e)
{
tbladdasset.Visible = true;
btnsaveasset.Enabled = true;
lblErrMsg.Text = "";
txtdescription.Text = "";
txtdtrecieved.Text = "";
txtcost.Text = "";
txtmodelno.Text = "";
txtquantity.Text = "";
}
protected void btnsaveasset_Click(object sender, EventArgs e)
{
if (txtdescription.Text != "" && txtdtrecieved.Text != "" && txtcost.Text != "" && txtmodelno.Text != "" && txtquantity.Text != "")
{
try
{
string desc= txtdescription.Text;
DateTime dtrecd = Convert.ToDateTime(txtdtrecieved.Text);
string cost = txtcost.Text;
string modelno = txtmodelno.Text;
double quantity = Convert.ToDouble(txtquantity.Text);
SqlConnection sqlcon = new SqlConnection(con);
sqlcon.Open();
string save = "Insert into Asset(Description,Recieveddate,cost,Modelno,Quantity)values(#desc,#date,#cost,#modelno,#quantity)";
SqlCommand cmd = new SqlCommand(save, sqlcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#desc", desc);
cmd.Parameters.Add("#date", dtrecd);
cmd.Parameters.Add("#cost", cost);
cmd.Parameters.Add("#modelno", modelno);
cmd.Parameters.Add("#quantity", quantity);
cmd.ExecuteNonQuery();
sqlcon.Close();
bindassets("", "");
btnsaveasset.Enabled = false;
txtdescription.Text = "";
txtdtrecieved.Text = "";
txtcost.Text = "";
txtmodelno.Text = "";
txtquantity.Text = "";
lblErrMsg.Text = "data inserted successfully..";
}
catch
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
}
else
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
}
protected void grdvAssets_Sorting(object sender, GridViewSortEventArgs e)
{
bindassets(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;
}
}
Anyone please help me.....Thanks in advance..
that's a common problem. check similar SO questions: Webforms Refresh problem, How to stop unwanted postback.
if a few words, web browser refresh button just sends the last request to the server in your case that's a "Save" button click event, thus it gives duplicate rows. use Response.Redirect, this way the last request will be just navigation to the page, so the refresh will not cause undesired effects.
EDITED
I see you have added some code. here's a workaround for you. the fact that you are saving data to database helps a lot. first thing on page load event no need to check if page IsPostBack, just call the bindassets("", ""); method.
as for save button click event. no need to call the bindassets("", ""); it will be called from page load.
protected void btnsaveasset_Click(object sender, EventArgs e)
{
if (txtdescription.Text != "" && txtdtrecieved.Text != "" && txtcost.Text != "" && txtmodelno.Text != "" && txtquantity.Text != "")
{
try
{
string desc= txtdescription.Text;
DateTime dtrecd = Convert.ToDateTime(txtdtrecieved.Text);
string cost = txtcost.Text;
string modelno = txtmodelno.Text;
double quantity = Convert.ToDouble(txtquantity.Text);
SqlConnection sqlcon = new SqlConnection(con);
sqlcon.Open();
string save = "Insert into Asset(Description,Recieveddate,cost,Modelno,Quantity)values(#desc,#date,#cost,#modelno,#quantity)";
SqlCommand cmd = new SqlCommand(save, sqlcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#desc", desc);
cmd.Parameters.Add("#date", dtrecd);
cmd.Parameters.Add("#cost", cost);
cmd.Parameters.Add("#modelno", modelno);
cmd.Parameters.Add("#quantity", quantity);
cmd.ExecuteNonQuery();
sqlcon.Close();
//bindassets("", "");
btnsaveasset.Enabled = false;
txtdescription.Text = "";
txtdtrecieved.Text = "";
txtcost.Text = "";
txtmodelno.Text = "";
txtquantity.Text = "";
lblErrMsg.Text = "data inserted successfully..";
}
catch
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
}
else
{
lblErrMsg.Text = "Please enter valid data and try again...";
}
Response.Redirect("nameofpage.aspx", false);//does a charm. browser refresh button will repeat last action and from now on that's a Response.Redirect("nameofpage.aspx", false). thus no duplicate records
}
if (!IsPostBack)
{
Bind(); //bind data to grid
}

Categories

Resources