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

You are currently viewing the ASP.NET 2.0 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 21st, 2008, 04:35 AM
Authorized User
 
Join Date: Jan 2008
Location: , , .
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default Getting a databound value from datalist contrrol

Hi,i have this simple question here.
Assuming i have a database with 2 data fields which looks like the following

Name Age
Alan 23
Frank 44
Paul 43

if i use a datalist control,it's going to show me the name and age labels and values which will be 3 columns.How do i store the name and age value in variables based on what column that i want ?

Ex:let's say if i want column 2 name and age(Frank 44)stored in 2 different variables?
Dim name as string = ??
Dim age as integer =??


thanks

 
Old January 21st, 2008, 11:02 AM
Friend of Wrox
 
Join Date: Jun 2003
Location: , , USA.
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

Here's one way to go. I'm pretty sure the item values you want won't be available on postbacks without hitting the database again. For example, I think the list SelectedItem.DataItem property is always null after the initial DataBind.

You can add a key field to your database table ("id"), then add a DataKeyField property to your DataList (DataKeyField="id"). Set the variable values in the OnItemCommand event by passing the DataKeyField value to the database, and retrieve a result set containing the field values of the DataList row you selected.

[code<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

void Item_Command(Object sender, DataListCommandEventArgs e)
{
    string name = String.Empty;
    string age = String.Empty;

    int keyField = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);

    // Hit the Database
    string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandType = CommandType.Text;
            command.CommandText = "SELECT * FROM Table1 WHERE id = " + keyField;

            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                     name = (reader["name"]).ToString();
                     age = (reader["age"]).ToString();
                }
            }
        }
    }

    Label1.Text = String.Format("You selected: Name: {0}, Age: {1}", name, age);
}

</script>
<head>
    <title>DataList Select </title>

</head>
<body>

   <form id="form1" runat="server">

      Click <b>Select</b> to store list items in variables.

      <br /><br />

       <asp:DataList ID="DataList1" runat="server"
                      DataSourceID="SqlDataSource1"
                      OnItemCommand="Item_Command"
                      DataKeyField="id"
                      >
            <HeaderTemplate><h3>Names and Ages</h3></HeaderTemplate>
            <ItemTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:LinkButton id="SelectButton" Text="Select" CommandName="Select" runat="server"/>&nbsp;
                        </td>
                        <td>Name:</td>
                        <td><asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />&nbsp;</td>
                        <td>Age:</td>
                        <td><asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' /></td>
                    </tr>
                </table>
            </ItemTemplate>
            <SeparatorTemplate>

            </SeparatorTemplate>
        </asp:DataList>&nbsp;
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
            SelectCommand="SELECT * FROM Table1"
            SelectCommandType="Text">
      </asp:SqlDataSource>
      <br />
      <asp:Label ID="Label1" runat="server"></asp:Label>
   </form>
</body>
</html>
[/code]

HTH,

Bob



 
Old January 21st, 2008, 11:09 AM
Friend of Wrox
 
Join Date: Jun 2003
Location: , , USA.
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

Just noticed you're using VB, but the conversion is pretty straight forward. Happy to help you with it if you need a hand. :)

Bob

 
Old January 21st, 2008, 11:08 PM
Authorized User
 
Join Date: Jan 2008
Location: , , .
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Bob,
Thanks lots for the suggestion.However,i have to apologize because i did not state some important factors.First of all,i'm grabbing the data from my company's database which i'm only allowed to read.Therefore,i can't add in a key field(ID)to the database and i'm sure there are no fields which are set as a primary key.Second,i'm not suppose to add any linkbuttons to my datalist item templates.Only two labels which are name and age.So the question still remains,how do i get the those values to put into a variable.Thanks.

 
Old January 21st, 2008, 11:48 PM
Wrox Author
Points: 13,255, Level: 49
Points: 13,255, Level: 49 Points: 13,255, Level: 49 Points: 13,255, Level: 49
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2005
Location: Ohio, USA
Posts: 4,104
Thanks: 1
Thanked 64 Times in 64 Posts
Send a message via AIM to dparsons
Default

You do not necessarily need a Primary Key field but you do need a field that is guranteed to be unique (an identity column) for Bobs approach to work. First I would speak to your DBA and make sure that there is not some sort of unique field on the database and, if there isn't you could follow an approach similar to this (I am going to reuse most of Bobs code for consistancey sake):
Code:
<%@ Page Language="C#"  %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

protected void DataList1_ItemDataBound(object sender, 
        DataListItemEventArgs e)
{
   if(e.Item.ItemType == ListItemType.Item || 
          e.Item.ItemType == ListItemType.AlternatingItem)
   {
       LinkButton lb = (LinkButton)e.Item.FindControl("SelectButton");
       lb.Command += new CommandEventHandler(LinkButton1_Command);
    }
}

    protected void LinkButton1_Command(object sender, CommandEventArgs e)
    {
Label1.Text = String.Format("You selected: Name: {0}, Age: {1}", e.CommandName.ToString(), e.CommandArgument.ToString());
    }

</script>
<head>
    <title>DataList Select </title>

</head>
<body>

   <form id="form1" runat="server">

      Click <b>Select</b> to store list items in variables.

      <br /><br />

       <asp:DataList ID="DataList1" runat="server" 
                      DataSourceID="SqlDataSource1" 
                      onitemdatabound="DataList1_ItemDataBound"
                      >
            <HeaderTemplate><h3>Names and Ages</h3></HeaderTemplate>
            <ItemTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:LinkButton id="SelectButton" Text="Select" CommandName='<%# Eval("Name") %>' CommandArgument='<%# Eval("Age") %>' runat="server"/>&nbsp;
                        </td>
                        <td>Name:</td>
                        <td><asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />&nbsp;</td>
                        <td>Age:</td>
                        <td><asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' /></td>
                    </tr>
                </table>
            </ItemTemplate>
            <SeparatorTemplate>

            </SeparatorTemplate>
        </asp:DataList>&nbsp;
      <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
            SelectCommand="SELECT * FROM Table1" 
            SelectCommandType="Text">
      </asp:SqlDataSource>
      <br />
      <asp:Label ID="Label1" runat="server"></asp:Label>
   </form>
</body>
</html>
This is somewhat of a hack, but it should work for you. (Again I should stress speaking with your DBA as I prefer Bob's method over the one I have provided here.)

hth.


================================================== =========
Read this if you want to know how to get a correct reply for your question:
http://www.catb.org/~esr/faqs/smart-questions.html
================================================== =========
.: Wrox Technical Editor / Author :.
Wrox Books 24 x 7
================================================== =========
 
Old January 21st, 2008, 11:55 PM
Friend of Wrox
 
Join Date: Jun 2003
Location: , , USA.
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

If you aren't allowed to place any controls on the DataList to select the values you want, I'm afraid I have no idea how you're going to select the values you want. I'm not even going to touch the primary key issue :).

Best,

Bob

 
Old January 22nd, 2008, 01:37 AM
Friend of Wrox
 
Join Date: Jun 2003
Location: , , USA.
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

In version 2, I think you'll need to raise the event through the OnCommand method of the link button though.

<asp:LinkButton id="SelectButton" Text="Select"
           CommandName='<%# Eval("Name") %>'
           CommandArgument='<%# Eval("Age") %>'
           OnCommand=LinkButton1_Command

I'm not sure, I don't think you can attach a delegate to a control contained within another control at:

lb.Command += new CommandEventHandler(LinkButton1_Command);

At least I can't get the event to fire wired up that way. But using the OnCommand method works fine.

Best,

Bob




 
Old January 24th, 2008, 01:49 AM
Authorized User
 
Join Date: Jan 2008
Location: , , .
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thanks lots Bob and Dparsons,your codes really helped me lots!

 
Old April 23rd, 2008, 09:00 AM
Authorized User
 
Join Date: Jan 2008
Location: , , .
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:Originally posted by dparsons
 You do not necessarily need a Primary Key field but you do need a field that is guranteed to be unique (an identity column) for Bobs approach to work. First I would speak to your DBA and make sure that there is not some sort of unique field on the database and, if there isn't you could follow an approach similar to this (I am going to reuse most of Bobs code for consistancey sake):
Code:
<%@ Page Language="C#"  %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<script runat="server">

protected void DataList1_ItemDataBound(object sender, 
        DataListItemEventArgs e)
{
   if(e.Item.ItemType == ListItemType.Item || 
          e.Item.ItemType == ListItemType.AlternatingItem)
   {
       LinkButton lb = (LinkButton)e.Item.FindControl("SelectButton");
       lb.Command += new CommandEventHandler(LinkButton1_Command);
    }
}

    protected void LinkButton1_Command(object sender, CommandEventArgs e)
    {
Label1.Text = String.Format("You selected: Name: {0}, Age: {1}", e.CommandName.ToString(), e.CommandArgument.ToString());
    }

</script>
<head>
    <title>DataList Select </title>

</head>
<body>

   <form id="form1" runat="server">

      Click <b>Select</b> to store list items in variables.

      <br /><br />

       <asp:DataList ID="DataList1" runat="server" 
                      DataSourceID="SqlDataSource1" 
                      onitemdatabound="DataList1_ItemDataBound"
                      >
            <HeaderTemplate><h3>Names and Ages</h3></HeaderTemplate>
            <ItemTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:LinkButton id="SelectButton" Text="Select" CommandName='<%# Eval("Name") %>' CommandArgument='<%# Eval("Age") %>' runat="server"/>&nbsp;
                        </td>
                        <td>Name:</td>
                        <td><asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />&nbsp;</td>
                        <td>Age:</td>
                        <td><asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' /></td>
                    </tr>
                </table>
            </ItemTemplate>
            <SeparatorTemplate>

            </SeparatorTemplate>
        </asp:DataList>&nbsp;
      <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
            SelectCommand="SELECT * FROM Table1" 
            SelectCommandType="Text">
      </asp:SqlDataSource>
      <br />
      <asp:Label ID="Label1" runat="server"></asp:Label>
   </form>
</body>
</html>
This is somewhat of a hack, but it should work for you. (Again I should stress speaking with your DBA as I prefer Bob's method over the one I have provided here.)

hth.


================================================== =========
Read this if you want to know how to get a correct reply for your question:
http://www.catb.org/~esr/faqs/smart-questions.html
================================================== =========
.: Wrox Technical Editor / Author :.
Wrox Books 24 x 7
================================================== =========

hi,
by looking at your codes above,how do i control the visiblity of the datalist based on a dataitem in a field.Example:my table which contains 3 fields:
Name Age Display
john 1 Y
lucy 2 N
victor 3 Y

What codes should i add to yours to allow the datalist to only display the data with Display field =Y? Please advice.Thanks

Regards,
alvin





Similar Threads
Thread Thread Starter Forum Replies Last Post
Databound Dropdown fullingdale ASP.NET 2.0 Basics 2 June 20th, 2008 02:33 AM
asp databound dropdownlist kent ASP.NET 1.0 and 1.1 Basics 7 June 2nd, 2008 09:07 AM
VS2005 DataGridViewComboBoxColumn databound CloudDust Visual Basic 2005 Basics 4 October 12th, 2006 06:29 PM
databound headertemplate collie VB.NET 2002/2003 Basics 0 March 7th, 2005 10:31 AM
Databound List Box Kunkel VS.NET 2002/2003 2 November 7th, 2003 01:38 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.