Asp.Net:使用Datalist中的buttoncontrol从Datalist中检索行数据

时间:2013-08-16 07:17:04

标签: asp.net sql-server-2008

我有一个Datalist,在itemtemplate里面我有两个标签和一个按钮。 我想检索datalist行的行数据。

我的.aspx页面是:

<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
     <HeaderTemplate>

     </HeaderTemplate>
     <ItemTemplate>
         <table width="100%">
             <tr>
                 <td>
                     <asp:Label ID="lblid11" runat="server" Text='<%#Eval("SubMenu_Id") %>' />
                 </td>
                 <td>
                     <asp:Label ID="lblid12" runat="server" Text='<%#Eval("SubMenu_Name") %>' />
                 </td>
                 <td>
                     <asp:Label ID="lblid13" runat="server" Text='<%#Eval("SubMenu_Price") %>' />
                 </td>
                 <td>
                     <asp:Button ID="btninside" runat="server" CommandName="call" Text="click me" onclick="btninside_Click" />
                 </td>
             </tr>
         </table>
     </ItemTemplate>

 </asp:DataList>

和我的.CS页面是

public partial class Datalist_Button : System.Web.UI.Page
{
    string s = WebConfigurationManager.ConnectionStrings["FoodPlanetConnectionString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataList();
        }
    }

    public void BindDataList()
    {
        SqlConnection con = new SqlConnection(s);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Menu", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataList1.DataSource = ds;
        DataList1.DataBind();
        con.Close();
    }

    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "call")
        {
            DataListItem item = (DataListItem)(((Button)(e.CommandSource)).NamingContainer);
            string text = ((Label)item.FindControl("lblid12")).Text;
        }

    }

请帮助我,我的代码不能正常工作

1 个答案:

答案 0 :(得分:0)

试试这个。

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "call")
        {
            string text = ((Label)DataList1.Items[e.Item.ItemIndex].FindControl("lblid12")).Text;
        }
    }