Use ContentEditable to Save Into DB With ASP.NET? - c#

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)
{
(...)
}
}

Related

No value given for one or more required parameters - C#/Access

This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";

ASP.NET C# Validating username and password

Im trying to validate username and password from an MySql server. Login validation is working, but I can't for the life of me figure out why the "Create new user" validation isn't working.
Here are the code for registering new user. What happens is;
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
Seems like this part ^ is ruining it for me somehow, whenever i test run this code I get this message.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=user; Password=password";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
EDIT:
If I try it like this:
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
String sql = "SELECT * FROM user";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect);
da = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
ds = new DataSet("TEST");
da.Fill(ds, "user");
Response.Write(ds.Tables["user"].Rows.Count);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
This ends up with the possibility of making a user without username or password.
There are a number of things that could be going wrong. You should examine the exception.message to get insights as to what it could be.
For example, put a break point in the catch statement and see if the exception thrown for things like... does the username already exist and SQL is throwing an error. ... or are the username/password null, too long, etc...
Regardless, change the catch statement to catch(Exception exception) and see what the exception is.
I want to thank everyone for trying, found a working solution, will post it here for future reference.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
if (!string.IsNullOrWhiteSpace(inputUser.Text) && !string.IsNullOrWhiteSpace(inputPw.Text))
{
dbconnect.Open();
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
string qry = "INSERT INTO user(username, password) VALUES (#un, #pw)";
cmd = new MySqlCommand(qry, dbconnect);
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
cmd.ExecuteNonQuery();
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}

calling 2 methods from onclick c#

Ive been trying to pass 2 SQL queries by clicking the button once and so this is what ive been trying to do as shown below but its not working....please help... thanks in advance
so this the code in front
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click1; btnWedRecInsert_Click2;" />
The code behind is below
protected void btnWedRecInsert_Click1(object sender, EventArgs e)
{
string Function = ddlFunction.Text;
string FunctionDate = txtFunctionDate.Text;
string FunctionTime = ddlFunctionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
protected void btnWedRecInsert_Click2(object sender, EventArgs e)
{
string Function = ddlReception.Text;
string FunctionDate = txtReceptionDate.Text;
string FunctionTime = ddlReceptionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, ReceptionTime, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
You should change your markup to:
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click" />
And change your codebehind to:
protected void btnWedRecInsert_Click(object sender, EventArgs e)
{
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}
and for readability maybe you should change the name of the insert functions to
insertWedding1();
insertWedding2();
As of now I can't see any difference between the two insertfunctions. mayby you will change theese later but they're quite similar. How about making a function out of them with parameters so you don't have to write so much code : ) eg.
insertWedding(object paramWedding1);
insertWedding(object paramWedding2);
Change the onClick event to btn_{NameOfYourButton}Click and then have
public void btn_{NameOfYourButton}Click() {
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}

Update Database with Textboxes

I'm trying to get these textboxes to show data from a database, i'm able to show the data but everytime I try to update it won't save. Here's what i've done
private void ClubRecord_Load(object sender, EventArgs e)
{
try
{
sConnection = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = Eastern_Property_Maintenance.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Club ORDER BY CompanyName, CompanyAddress, CompanyPhone;";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbreader = dbCmd.ExecuteReader();
while (dbreader.Read())
{
string CompanyName = dbreader["CompanyName"].ToString();
string CompanyAddress = dbreader["CompanyAddress"].ToString();
string CompanyPhone = dbreader["CompanyPhone"].ToString();
txtCompanyName.Text = CompanyName;
txtCompanyAddress.Text = CompanyAddress;
txtCompanyPhone.Text = CompanyPhone;
}
dbreader.Close();
// dbConn.Close();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = "UPDATE [Club] SET [CompanyName]= #CompanyName,[CompanyAddress]=#CompanyAddress,[CompanyPhone]=#CompanyPhone";
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
Any help would be greatly appreciated thanks.
It is a subtle typo error, but I think that there is something to learn here, so I want to give a full answer:
You create a command called dbcmd
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
but then you fill the parameter collection of a different command dbCmd and executes this one.
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
C# is case sensitive, so the twos are not the same command, but how does it lead to the failed update is worth to look at.
You have declared a global OleDbCommand variable named dbCmd and this variable is still set to the SELECT query used to load the textboxes. So, when you call ExecuteNonQuery it does not update anything.
You could fix the problem simply changing all the references in the updated code from dbCmd to dbcmd. But, the lesson to learn here is, when possible avoid to use global variables.
The Connection is another example of a global variable and this is worst because it is left open after the initial form load. Don't do that. Connectiosn keep valuable system resources locked and thus should be closed immediately after usage applying the using statement pattern
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = #"UPDATE [Club] SET [CompanyName]= #CompanyName,
[CompanyAddress]=#CompanyAddress,
[CompanyPhone]=#CompanyPhone"; // A where here should be mandatory
using(OleDbConnection dbConn = new OleDbConnection(aGlobalConnectionStringWouldBeSafeHere))
using(OleDbCommand dbcmd = new OleDbCommand(Update, dbConn))
{
dbcmd.Parameters.AddWithValue("#CompanyName", companyName);
dbcmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbcmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbcmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
}
By the way, I hope that your table contains only one record because without a WHERE clause you update every record present with the values of your textboxes.

Handling multiple buttons in same asp.net page

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

Categories

Resources