473,385 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Page_load

Hi all,
what i'm trying to do here is when i open a page, it goes to a db and pull some info and display it in a textbox, then if i edit that text box, and hit save, it gets updated it in database.

I'm establishing a connection to the db under protected void Page_Load (object sender, EventArgs e) and it is getting the value correctly, below is the code for that.

Expand|Select|Wrap|Line Numbers
  1.  
  2. SqlConnection conn;
  3. conn = new SqlConnection("Data Source=SQLServer;Initial Catalog=I3_IC;Persist Security Info=True;User ID=username;Password=password");
  4.  
  5. SqlDataReader rdr = null;
  6.  try
  7.    {
  8.      conn.Open();
  9.      SqlCommand cmd = new SqlCommand("select Updateable_Message from UpdateableMessage", conn);
  10.  
  11.     rdr = cmd.ExecuteReader();
  12.  
  13.     while (rdr.Read())
  14.        {
  15.         TextBox.Text = rdr[0].ToString();
  16.        }
  17.   }
  18.  
  19.  finally
  20.        {
  21.         // close the reader
  22.         if (rdr != null)
  23.            {
  24.                  rdr.Close();
  25.             }
  26.  
  27.         // Close the connection
  28.         if (conn != null)
  29.             {
  30.                 conn.Close();
  31.              }
  32.             }
Below is my code for the save button
Expand|Select|Wrap|Line Numbers
  1.  
  2.  protected void ButtonSave_Click(object sender, EventArgs e)
  3.     {
  4.  
  5.  
  6.         SqlDataSource dashDataSource = new SqlDataSource();
  7.         dashDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString1"].ToString();
  8.  
  9.         dashDataSource.InsertCommandType = SqlDataSourceCommandType.Text;
  10.         dashDataSource.InsertCommand = "Update UpdateableMessage set Updateable_Message = @strUpdateMessage";
  11.  
  12.         dashDataSource.InsertParameters.Add("strUpdateMessage", TextBox.Text);
  13.         int rowsAffected = 0;
  14.  
  15.         try
  16.         {
  17.             rowsAffected = dashDataSource.Insert();
  18.         }
  19.  
  20.         catch (Exception ex)
  21.         {
  22.             Server.Transfer("Problem.aspx");
  23.         }
  24.  
  25.         finally
  26.         {
  27.             dashDataSource = null;
  28.         }
  29.  
  30.         if (rowsAffected != 1)
  31.         {
  32.             //Server.Transfer("Problem.aspx");
  33.             LabelResult.Text = "The Hot Topic Message hasn't been updated successfully";
  34.         }
  35.         else
  36.         {
  37.             LabelResult.Text = "The Hot Topic Message has been updated successfully";
  38.             TextBox.Text = "";
  39.  
  40.             //  Server.Transfer("AddRecords.aspx");
  41.  
  42.         }
  43.  
  44.     }
  45.  
Now, if i hit save, it doesn't update!
if i removed the code from the Page_load, and when i first load the page, i don't see what is in the db Obviously and if i hit save the data in the text file gets saved successfully.

it is like either or :(
I'm sure there is way around it, but how?
any feedback is appriciated.

thanks in advance.
Mar 28 '08 #1
7 1671
balabaster
797 Expert 512MB
I don't think your code is doing exactly what you think it is...
In your page load, you're running off to the database with the connection string "Data Source=SQLServer;Initial Catalog=I3_IC;Persist Security Info=True;User ID=username;Password=password" and getting a list of items from your table (satisfied by the query "Select Updateable_Message from UpdateableMessage")...that list may contain 1 item or it may contain 100 - either way, the list of items you retrieve is of an arbitrary length defined by the number of items in the table in your database.

Once you've got your list of items, you're going to loop through the list and on each iteration of the loop, you're setting the value in the text box to the value of the current item in the list... as the textbox is only ever storing the value for the current iteration of your loop, I'm assuming that the table will only ever contain a single row - if that assumption is correct, then you may as well skip the loop using:
Expand|Select|Wrap|Line Numbers
  1. if(rdr.HasRows()){
  2.   rdr.read();
  3.   TextBox1.Text = rdr[0].ToString();
  4. }
Now, when you click your save button, are you updating your table or inserting a new item into your table? If you're updating which your design implies, you need the following:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand oUpdateCmd = New SqlCommand("Update MyTable Set MyField = @Value", oCon);
  2. oUpdateCmd.Parameters.Add(New SqlParameter("Value", TextBox1.Text);
  3. oUpdateCmd.ExecuteNonQuery();
If you're actually inserting, then you need:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand oInsertCmd = New SqlCommand("Insert Into MyTable(MyField) Values(@Value1)", oCon);
  2. oInsertCmd.Parameters.Add("Value1", TextBox1.Text);
  3. oInsertCmd.ExecuteNonQuery();
You will notice that other than the fact that my Sql query is different and I've named my variables differently, the two blocks of code are exactly the same structurally.

Does that make sense?
Mar 28 '08 #2
I don't think your code is doing exactly what you think it is...
In your page load, you're running off to the database with the connection string "Data Source=SQLServer;Initial Catalog=I3_IC;Persist Security Info=True;User ID=username;Password=password" and getting a list of items from your table (satisfied by the query "Select Updateable_Message from UpdateableMessage")...that list may contain 1 item or it may contain 100 - either way, the list of items you retrieve is of an arbitrary length defined by the number of items in the table in your database.

Once you've got your list of items, you're going to loop through the list and on each iteration of the loop, you're setting the value in the text box to the value of the current item in the list... as the textbox is only ever storing the value for the current iteration of your loop, I'm assuming that the table will only ever contain a single row - if that assumption is correct, then you may as well skip the loop using:
Expand|Select|Wrap|Line Numbers
  1. if(rdr.HasRows()){
  2.   rdr.read();
  3.   TextBox1.Text = rdr[0].ToString();
  4. }
Now, when you click your save button, are you updating your table or inserting a new item into your table? If you're updating which your design implies, you need the following:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand oUpdateCmd = New SqlCommand("Update MyTable Set MyField = @Value", oCon);
  2. oUpdateCmd.Parameters.Add(New SqlParameter("Value", TextBox1.Text);
  3. oUpdateCmd.ExecuteNonQuery();
If you're actually inserting, then you need:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand oInsertCmd = New SqlCommand("Insert Into MyTable(MyField) Values(@Value1)", oCon);
  2. oInsertCmd.Parameters.Add("Value1", TextBox1.Text);
  3. oInsertCmd.ExecuteNonQuery();
You will notice that other than the fact that my Sql query is different and I've named my variables differently, the two blocks of code are exactly the same structurally.

Does that make sense?
balabaster, thanks for your reply.
You are right about the loop, it is just one string from the field in the table. I will remove that..

about the save button, i actually updating that record and i can see it in the table if i don't have the the code in the page_load section. if i do have the code in the page_load the problem is once i hit save, it comes back with the old information!
Mar 29 '08 #3
balabaster
797 Expert 512MB
Oh, hehe, I just realised what the problem is - when you submit, page load fires again causing what you wrote to be replaced with what is in the database once more. To fix the problem, in your page_load method, wrap the code with:
Expand|Select|Wrap|Line Numbers
  1. if(!page.IsPostBack){
  2. //Do my stuff
  3. }
Now it will load what is in the database only when the page loads. So when you write in the textbox and hit send, it'll upload it to the database.
Mar 29 '08 #4
YOU ARE THE MAAAAAAAAAAAAAN...
thanks..

one more question....now when i enter the save button everything gets saved but when it comes back tellimg that the operation was sucessful, there is no data in the textbox... do i need to put a select code simmilar to the one in the page_load right after i update, within the protected void ButtonSave_Click(object sender, EventArgs e) ?
Thanks again.
Mar 29 '08 #5
balabaster
797 Expert 512MB
YOU ARE THE MAAAAAAAAAAAAAN...
thanks..

one more question....now when i enter the save button everything gets saved but when it comes back tellimg that the operation was sucessful, there is no data in the textbox... do i need to put a select code simmilar to the one in the page_load right after i update, within the protected void ButtonSave_Click(object sender, EventArgs e) ?
Thanks again.
Change the EnableViewState property of your textbox to be true instead of false.
Mar 29 '08 #6
got it... i was clearing it right after the sucessfull message. duh

thanks man for all your help
be the way, it did not like
Expand|Select|Wrap|Line Numbers
  1. if(rdr.HasRows())
  2. {
  3.   rdr.Read();
  4. TextBox.Text = rdr[0].ToString();
  5. }
  6.  
Compiler Error Message: CS1955: Non-invocable member 'System.Data.Common.DbDataReader.HasRows' cannot be used like a method.
Mar 29 '08 #7
balabaster
797 Expert 512MB
got it... i was clearing it right after the sucessfull message. duh

thanks man for all your help
be the way, it did not like
if(rdr.HasRows())
{
rdr.Read();
TextBox.Text = rdr[0].ToString();
}

Compiler Error Message: CS1955: Non-invocable member 'System.Data.Common.DbDataReader.HasRows' cannot be used like a method.
Try removing the () so it just says if(rdr.HasRows){ //stuff }

I need to get back to coding C# on a full time basis - my translation skills are starting to get rusty...I spend most of my time coding in VB now... it's all the same, just different syntax.
Mar 29 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Stevie_mac | last post by:
It might be me but... I dont seem to get a Page_Load event when a opening an ASPX in an iFrame. I do geta Page_Load event when an item on the ASPX (inside the iFrame) is clicked but then...
1
by: bminder | last post by:
In the asp.net pages below, Common.vb has an overridable Page_Load sub. In the consuming page, Two.aspx, the Page_Load sub is inherited, but for some reason it (Overrides Sub Page_Load) executes...
3
by: DavidS | last post by:
Have parent.aspx from which I open Driver.aspx form via button on parent.aspx. When I first open the modal dialog, the driver.aspx Page_Load function is called. After I close the dialog, then...
0
by: Itai | last post by:
Background: I have four Web Form pages with respective C# code behind files, all in the same project: localhost/vpath1 Page1.aspx Page2.aspx
14
by: V. Jenks | last post by:
I'm a little rusty having not touched .NET for 6 months and I can't remember why Page_Load is happening twice in this code: private void Page_Load(object sender, System.EventArgs e) {...
4
by: tshad | last post by:
Is there a way to do put Page_loads on a page? I am trying to setup a Page_Load that just puts a persons name that is logged on at the top of a page the first time a page is loaded. In my...
4
by: Seraph | last post by:
Again, I'm rather new here, so if I fail to follow any etiquette, please forgive me and let me know what I've done wrong, but I think this might interest quite a few people. One of my colleaques...
5
by: Andy | last post by:
Hi all, I have a site with the following architecture: Common.Web.dll - Contains a CommonPageBase class which inherits System.Web.UI.Page myadd.dll - Contains PageBase which inherits...
1
by: rockdale | last post by:
Hi, I have a masterpage and on the page_load event I Populate my mainmenu from database. I the page_load event of my content, I am trying to programmly select the menuitem that represent...
11
by: fiefie.niles | last post by:
I am using ASP.NET 2005 and I have a simple form. Page_Load calls a sub mySub that does not do anything (for testing purposes). But, Page_Load gets called twice. On every single ASPX page in my...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.