Handling multiple buttons in same asp.net page - c#

hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?

I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

Related

I can't seem to add or remove from database and update the datagrid based on the database. Why?

I am working on a library database where you can add and remove book from the database.
Button 1 problem
When I press the button1(add record to database and reload database in datagrid) it works on the first click of button1 and when I change what text in the textboxes(title, author, stock) to add to the database and click the button again, it doesn't change what is being added to the database.
example
textbox1.text(title)= "Harry potter" textbox2.text(author)="jk" textbox3.text(stock)="3"
button1(add) pressed. Works okay on the first click of button1. When I change the value of the textbox1-3
example
textbox1.text(title)= "alchemist" textbox2.text(author)="paollo cuello" textbox3.text(stock)="5"
it still record "Harry potter", "jk", and "3".
Button2 problem
When I press button 2(remove record in database and reload database in datagrid) it works on the first click but doesn't really show on the datagrid.
example.
datagrid shows values
title author stock
"harrypotter" "jk" 3 and
"alchemist" "pc" 4
textbox1.text(title)= "harrypotter" textbox2.text(author)="jk" textbox3.text(stock)="3"
button2(remove and reload datagrid) is pressed.
result = datagrid doesnt load the new records but harry potter record was deleted in the database
When I try to delete another record.
example.
title author stock
harrypotter jk 3
alchemist pc 4
notice that "harrypotter" still there because reload didnt work.
textbox1.text(title)= "alchemst" textbox2.text(author)="pc" textbox3.text(stock)="4"
button2(remove and reload datagrid) is pressed.
It doesn't work. I bet it was trying to delete the "harrypotter record still"
Why?
public partial class AddBook : Form
{
String title = "", author = "";
bool hasValue1 = false, hasValue2 = false, hasValue3 = false;
string holder = "";
int stock = 0;
OleDbConnection connect = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jc\Documents\Visual Studio 2013\Projects\itswn\Library System\Library System\LibrarySystemDatabase.accdb;Persist Security Info=True");
OleDbCommand command = new OleDbCommand();
OleDbDataReader reader;
public AddBook()
{
InitializeComponent();
}
private void AddBook_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("Title", "Title");
dataGridView1.Columns.Add("Author", "Author");
dataGridView1.Columns.Add("Stock", "Stock");
connect.Open();
loaddataBook();
}
private void loaddataBook()
{
int i = 0;
try
{
command.CommandText = "SELECT Title, Author, Stock FROM Book";
command.Connection = connect;
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells["Title"].Value = reader[0].ToString();
dataGridView1.Rows[i].Cells["Author"].Value = reader[1].ToString();
dataGridView1.Rows[i].Cells["Stock"].Value = reader[2].ToString();
i++;
}
}
reader.Close();
connect.Close();
}
catch (OleDbException ex)
{
connect.Close();
MessageBox.Show(ex.ToString());
}
connect.Close();
}
private void button1_Click(object sender, EventArgs e)
{
title = textBox1.Text.ToLower();
author = textBox2.Text.ToLower();
stock = int.Parse(textBox3.Text);
if (textBox1.Text != "")
{
hasValue1 = true;
}
if (textBox2.Text != "")
{
hasValue2 = true;
}
if (textBox3.Text != "")
{
hasValue3 = true;
}
if (int.Parse(textBox3.Text) >= 0 || textBox3.Text == "")
{
if (hasValue1 && hasValue2 && hasValue3)
{
try
{
connect.Open();
command.Connection = connect;
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#author", author);
command.Parameters.AddWithValue("#stock", stock);
command.CommandText = "INSERT INTO [Book](Title, Author, Stock) VALUES(#title, #author, #stock)";
command.ExecuteNonQuery();
loaddataBook();
connect.Close();
}
catch (OleDbException ex)
{
connect.Close();
MessageBox.Show(ex.ToString());
}
connect.Close();
}
else
{
label4.Text = "required";
label5.Text = "required";
label6.Text = "required";
}
}
else
{
MessageBox.Show("Stock should not be less than 0", "Keep in mind");
}
}
private void button2_Click(object sender, EventArgs e)
{
title = textBox1.Text.ToLower();
author = textBox2.Text.ToLower();
textBox3.Clear();
if (textBox1.Text != "")
{
hasValue1 = true;
}
if (textBox2.Text != "")
{
hasValue2 = true;
}
if (hasValue1 && hasValue2)
{
try
{
connect.Open();
command.Connection = connect;
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#author", author);
command.CommandText = "DELETE FROM [Book] WHERE Title = #title AND Author = #author";
command.ExecuteNonQuery();
loaddataBook();
connect.Close();
}
catch (OleDbException ex)
{
connect.Close();
MessageBox.Show(ex.ToString());
}
}
else
{
label4.Text = "required";
label5.Text = "required";
}
}
}
you should use the update function of the sql not insert function for example
update [tablename]
set [Book] = [valueof book] , [author ] = [valueofauthor] , so on~~
where statement you want to update~~~~
example where title = harrypotter.
this is for button1.

Populate dropdownlist with datareader from database

Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific dropdownlist that user selected before. Im using linqdatasource to show all the dropdownlist value.
public partial class Update : System.Web.UI.Page
{
string cs = Global.CS;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // only during initial load
{
string id = Request.QueryString["Item_ID"] ?? "";
string sql = "Select * FROM MenuItem WHERE Item_ID = #id";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Id", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
{
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
//foreach (var checking in db.Sets)
//{
// string setID = checking.Set_ID.ToString();
// if (setID == (string)dr["Item_ID"])
// {
// ddlAlacarte.DataSourceID = "ldsAlacarte";
// **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
// ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
// }
//}
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
}
}
else
{
Response.Redirect("MenuAdmin.aspx");
}
DataBind();
dr.Close();
con.Close();
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
{
ddlAlacarte.Enabled = true;
ddlBeverage.Enabled = true;
ddlSide.Enabled = true;
DataBind();
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
}
}
}
You need to add items in Dropdownlist while reading values.
Add the following code while you are reading values by using SqlDataReader.
while(dr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = dr["Category"].ToString();
listItem.Value = dr["Category"].ToString();
categoryDropDownList.Items.Add(listItem);
}
I would use something like this
dropDownList.Items.Add(
new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);
and iterate through, populating the dropdown list. Is that what you want ?

DataList keep displaying previously loaded datalist

I have a catalog function whereby user can filter their selection by clicking radiobutton. For example, by selecting the Dining radiobutton, all packages related to dining would appear.
And i using DataList1.Items.Count method to count the number search result. I had implement this method in the page_load, however the value of the number of datalist keep displaying previously loaded datalist.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT CategoryID, CatName from Category";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
//DataList1.DataSource = reader;
DataList1.DataBind();
// CommandBehavior.CloseConnection will automatically close connection
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataList1.DataSourceID = "SqlDataSource1";
if (RadioButtonList1.SelectedIndex == 0)
{
Session["catID"] = 1;
}
else if (RadioButtonList1.SelectedIndex == 1)
{
Session["catID"] = 2;
}
else if (RadioButtonList1.SelectedIndex == 2)
{
Session["catID"] = 3;
}
else if (RadioButtonList1.SelectedIndex == 3)
{
Session["catID"] = 4;
}
else if (RadioButtonList1.SelectedIndex == 4)
{
Session["catID"] = 5;
}
else
{
Session["catID"] = 8;
}
}
I had tried to place the Item.Count in other places of this code, but same problem persist..
Try this,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataList1.DataSourceID = "SqlDataSource3";
Label1.Text = DataList1.Items.Count.ToString();
}
}

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

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