ASP.NET Tutorial/Data Binding/ButtonField

Материал из .Net Framework эксперт
Версия от 11:59, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Use a ButtonField to display a button in a GridView

You can use a ButtonField to represent a custom command or one of the standard edit commands.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    protected void grdProductCategories_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Int32.Parse((string)e.rumandArgument);
        int id = (int)grdProductCategories.DataKeys[index].Values["Id"];
        int position = (int)grdProductCategories.DataKeys[index].Values["Position"];
        switch (e.rumandName)
        {
            case "Up":
               position--;
               break;
            case "Down":
               position++;
               break;
        }
        srcProductCategories.UpdateParameters["Id"].DefaultValue = id.ToString();
        srcProductCategories.UpdateParameters["Position"].DefaultValue = position.ToString();
        srcProductCategories.Update();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show ButtonField</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView
        id="grdProductCategories"
        DataSourceID="srcProductCategories"
        DataKeyNames="Id,Position"
        AutoGenerateColumns="false"
        OnRowCommand="grdProductCategories_RowCommand"
        Runat="server">
        <Columns>
        <asp:ButtonField
            Text="Move Up"
            CommandName="Up" />
        <asp:ButtonField
            Text="Move Down"
            CommandName="Down" />
        <asp:BoundField
            DataField="Position"
            HeaderText="Position" />
        <asp:BoundField
            DataField="Name"
            HeaderText="Category Name" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource
        id="srcProductCategories"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT Id, Name, Position FROM ProductCategories
            ORDER BY Position"
        UpdateCommand="UPDATE ProductCategories SET
            Position=@Position WHERE Id=@Id"
        Runat="server">
        <UpdateParameters>
        <asp:Parameter
            Name="Id" />
        <asp:Parameter
            Name="Position" />
        </UpdateParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

File: Web.config
<configuration>
  <connectionStrings>
    <add name="Products" 
         connectionString="Data Source=.\SQLEXPRESS;
         AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />
  </connectionStrings>
</configuration>