Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 3.5 > ASP.NET 3.5 Basics
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
ASP.NET 3.5 Basics If you are new to ASP or ASP.NET programming with version 3.5, this is the forum to begin asking questions. Please also see the Visual Web Developer 2008 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 3.5 Basics section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
 
 
Thread Tools Search this Thread Display Modes
  #11 (permalink)  
Old February 7th, 2011, 02:22 PM
Authorized User
Points: 160, Level: 3
Points: 160, Level: 3 Points: 160, Level: 3 Points: 160, Level: 3
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2004
Location: , , .
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Met betrekking tot 'De Vier Koe(r)den. Ik had mijn spelfout meteen door en gecorrigeerd. Het was wel een beetje genant!

I don't actually get to call databound explicitly as all the work is carried out for me...

Code:
<asp:CheckBoxList ID="cblGames" runat="server" 
                DataSourceID="SqlDataSource1" DataTextField="Game" DataValueField="Id">
            </asp:CheckBoxList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:Poker %>" 
                SelectCommand="SELECT [Id], [Game] FROM [Aanbod]"></asp:SqlDataSource>
When the page loads for the first time all checkboxes are blank. When the user clicks on a user name from a gridview table on the same page, the page reloads with the user profile/data and the checkboxes are checked accordingly. Well that doesn't happen. Alas...

From what I know of the page lifecycle. The aspx.page, of which the code above is a part, is processed before the code-behind, so the values are present when the check routine works:

HTML Code:
if    (!Page.IsPostBack && Request.QueryString["id"] != null)
        {
            SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Poker.mdf;Integrated Security=True;User Instance=True");
            string sql = "SELECT g.Id, g.Gender, g.NameToDisplay, g.AdditionalInfo, g.SpecifiedTime, g.PhysicalStatus, a.Game, a.Id AS AanbodId, i.GastId FROM  Aanbod AS a INNER JOIN Inschrijving AS i ON a.Id = i.AanbodId INNER JOIN Gast AS g ON i.GastId = g.Id WHERE i.GastID = @GastId";
            SqlCommand comm = new SqlCommand(sql, conn);
            conn.Open();

            comm.Parameters.AddWithValue("@GastId", Request.QueryString["Id"]);
            SqlDataReader reader = comm.ExecuteReader();
            
            string specifiedTime = System.String.Empty;
            string gender = System.String.Empty;
            string physicalStatus = System.String.Empty;
            string gid = System.String.Empty;

            while (reader.Read())
            {
                specifiedTime = Convert.ToString(reader["SpecifiedTime"]);
                gender = Convert.ToString(reader["Gender"]);
                physicalStatus = Convert.ToString(reader["PhysicalStatus"]);

                // Populate form from database
                NameToDisplay.Text = reader["NameToDisplay"].ToString();
                AdditionalInfo.Text = Convert.ToString(reader["AdditionalInfo"]);
                Gender.SelectedValue = Convert.ToString(Gender.Items.FindByValue(gender).Value);
                PhysicalStatus.SelectedValue = Convert.ToString(PhysicalStatus.Items.FindByValue(physicalStatus).Value);
                SpecifiedTime.SelectedValue = Convert.ToString(SpecifiedTime.Items.FindByValue(specifiedTime).Value);

                ListItem currentCheckBox = cblGames.Items.FindByValue(reader["AanbodId"].ToString());
                
                if (currentCheckBox != null)
                {
                    currentCheckBox.Selected = true;
                }
                
                Label1.Text += (reader["AanbodId"].ToString)();
            }
        }
As I say if the form values are hard coded then the check routine works:

HTML Code:
<asp:CheckBoxList ID="cblGames" runat="server">
                <asp:ListItem Value="1">Text1</asp:ListItem>
                <asp:ListItem Value="2">Text2</asp:ListItem>
                <asp:ListItem Value="3">Text2</asp:ListItem>
            </asp:CheckBoxList>
Are my above assumptions correct?

regards, Guy
  #12 (permalink)  
Old February 7th, 2011, 03:48 PM
Imar's Avatar
Wrox Author
Points: 72,055, Level: 100
Points: 72,055, Level: 100 Points: 72,055, Level: 100 Points: 72,055, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,086
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

Haha, geeft niks. Ik heb er drie maanden overgedaan om de Postbank zo ver te krijgen dezelfde fout te herstellen bij de naamstelling van m'n bankrekening ;-)

Anyway:
Quote:
Are my above assumptions correct?
Some of them. It isn't necessarily true that code in Markup fires before code in Code Behind. Take the SqlDataSource for example, It fires its selecting code during the data binding process which is after Page_Load. So, consider this:

Code:
 
protected void Page_Load(object sender, EventArgs e)
{
  int count = cblGames.Items.Count
}
in combination with your DropDownList and SqlDataSource control. What's the value of count after this code has executed?

The answer is: it depends. When the page loads the first time, data binding hasn't taken place, so the items from the SqlDataSource are not present in the DropDownList. As soon as the page posts back, the DropDownList is reconstructed from ViewState and has a count greater than zero.

Now, consider your code:

Code:
 
protected void Page_Load(object sender, EventArgs e)
{
  ListItem listItem = cblGames.Items.FindByValue("1");
  if (listItem != null)
  {
    listItem.Selected = true;
  }
  int count = cblGames.Items.Count;
}
What does this code do? Again, the answer: is depends. If the page loads the first time, data binding hasn't taken place, the DropDownList is empty, listItem will be null and nothing gets selected. If you post back, the DropDownList is filled and this code selects the item (provided there's an item with a value of "1").

Now, if I understand you correctly, you want to preselect the item the first time the page loads. As you saw, data binding takes place after your code so you're a bit too late. To speed things up, you can force the DropDownList control to data bind earlier by calling DataBind explicitly like this:

Code:
protected void Page_Load(object sender, EventArgs e)
{
  cblGames.DataBind();
  ListItem listItem = cblGames.Items.FindByValue("1");
  if (listItem != null)
  {
    listItem.Selected = true;
  }
  int count = cblGames.Items.Count;
}

What happens this time? Since you force the list to bind, the items are present and the code can successfully preselect the item. Unfortunately, on PostBack you actually overwrite the user's selection. You can fix that as per your own code: only call this when the page doesn't post back. So, here's the complete example that should work:

Code:
protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    cblGames.DataBind();
    ListItem listItem = cblGames.Items.FindByValue("1");
    if (listItem != null)
    {
      listItem.Selected = true;
    }
    int count = cblGames.Items.Count;
  }
}
For the record, and so I can stop suggesting the same fix in each and every post I make: did you try calling cblGames.DataBind() *before* you try to find the currently selected item in the list? E.g. directly after your first if() check?

Code:
 
if (!Page.IsPostBack && Request.QueryString["id"] != null)
{
  cblGames.DataBind();
}
Hope this clarifies things.

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
  #13 (permalink)  
Old February 7th, 2011, 11:18 PM
Authorized User
Points: 160, Level: 3
Points: 160, Level: 3 Points: 160, Level: 3 Points: 160, Level: 3
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2004
Location: , , .
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Imar,

It works! The Eureka moment soon gave way to sentiments of 'Jeetje jongen, je had jezelf een hoop ellende kunnen besparen als je maar je hersens had gebruikt...'

To answer your question about whether I had tried using cblGames.DataBind() in the code behind. I had tried it before but it hadn't worked. The reason for it not working before was that I hadn't implemented it correctly.

Markup: <asp:CheckBoxList ID="cblGames" runat="server"
DataTextField="Game" DataValueField="Id">
</asp:CheckBoxList>

HTML Code:
 if (!Page.IsPostBack)
  {
      SqlConnection connGames = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Poker.mdf;Integrated Security=True;User Instance=True");
      string sqlGames = "SELECT Id, Game FROM Aanbod WHERE ShowWaitingList = 'true'";
      SqlCommand commGames = new SqlCommand(sqlGames, connGames); connGames.Open();
      cblGames.DataSource = commGames.ExecuteReader();
      cblGames.DataBind();
  }
When requesting an existing user's choices it would check the boxes. However, when entering a new user into the system, only their profile made it to the insert. The checkbox selections were discarded somewhere along the way. Is this because the checkbox list doesn't get any field/value combinations on pageload, leading to their removal from the postback data, and therefore not making it as far as the data processing routine?

Anyway, what I should have done, and apologize for not having done so, is give you the feedback necessary to help me as efficiently and quickly as possible. Thanks for your help.

Regards,

Guy

Last edited by guynorton; February 7th, 2011 at 11:31 PM..
  #14 (permalink)  
Old February 8th, 2011, 03:46 AM
Imar's Avatar
Wrox Author
Points: 72,055, Level: 100
Points: 72,055, Level: 100 Points: 72,055, Level: 100 Points: 72,055, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,086
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

Quote:
The checkbox selections were discarded somewhere along the way. Is this because the checkbox list doesn't get any field/value combinations on pageload, leading to their removal from the postback data, and therefore not making it as far as the data processing routine?
No, I don't think so. The code you posted should have worked. You wrapped the data binding in !Page.IsPostBack so it only takes place o the initial load. With a postback, the selected items should have been preserved. I think the problem may have been elsewhere with your code.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
  #15 (permalink)  
Old February 8th, 2011, 10:54 AM
Authorized User
Points: 160, Level: 3
Points: 160, Level: 3 Points: 160, Level: 3 Points: 160, Level: 3
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2004
Location: , , .
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Imar,

Re 'I think the problem may have been elsewhere with your code.....'

Well there go my aspirations of being the Sherlock Holmes of code debugging!

Sincerely, Doctor Watson
  #16 (permalink)  
Old February 8th, 2011, 10:58 AM
Imar's Avatar
Wrox Author
Points: 72,055, Level: 100
Points: 72,055, Level: 100 Points: 72,055, Level: 100 Points: 72,055, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,086
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

I guess you have to be Sherlock here, as I haven't seen enough code to make justified suggestions... ;-) What you posted shouldn't be causing the problem...

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
accessing property from code behind in .ascx reks_dnet ASP.NET 1.0 and 1.1 Professional 1 May 23rd, 2007 08:35 AM
User.Identity.Name and accessing it from code CodeBugger C# 3 May 24th, 2006 04:41 PM
Accessing Drawing Objects from code isuru Excel VBA 0 August 29th, 2005 11:45 PM
Accessing Web User Controls from code aquaboltar ASP.NET 2.0 Basics 0 October 26th, 2004 04:04 PM



All times are GMT -4. The time now is 06:16 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.