DataGrid學習七

來源:互聯網
上載者:User
datagrid 上一例中BoundColumn 控制項不是唯一可以在 DataGrid 的 Columns 集合中設定的控制項。還可以指定 TemplateColumn,它使您可以完全控制列的內容。模板的內容可以是任意的;在 DataGrid 的列中可以呈現任何內容,包括伺服器控制項。下面的樣本說明如何使用 TemplateColumn 控制項將“State”列呈現為下拉式清單並將“Contract”列呈現為複選框 HtmlControl。ASP.NET 資料繫結文法用於輸出模板中的資料欄位值。注意,有一些棘手的邏輯使下拉式清單和複選框反射行中的資料狀態。



<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
    SqlConnection myConnection;
    public Hashtable StateIndex;



    protected void Page_Load(Object Src, EventArgs E)
    {
        myConnection = new SqlConnection("user id=sa;password=;initial catalog=pubs;data source=jeff");



        if (!IsPostBack)
            BindGrid();
         StateIndex = new Hashtable();
         StateIndex["CA"] = 0;
         StateIndex["IN"] = 1;
         StateIndex["KS"] = 2;
         StateIndex["MD"] = 3;
         StateIndex["MI"] = 4;
         StateIndex["OR"] = 5;
         StateIndex["TN"] = 6;
         StateIndex["UT"] = 7;
    }



    public int GetStateIndex(String stateName)
    {
        if (StateIndex[stateName] != null)
            return (int)StateIndex[stateName];
        else
            return 0;
    }



    public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
        BindGrid();
    }



    public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = -1;
        BindGrid();
    }



    public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
    {
        String updateCmd = "UPDATE Authors SET au_id = @Id, au_lname = @LName, au_fname = @FName, phone = @Phone, "
             + "address = @Address, city = @City, state = @State, zip = @Zip, contract = @Contract where au_id = @Id";
        SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);
        myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar, 11));
        myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar, 40));
        myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar, 20));
        myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar, 12));
        myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));
        myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 20));
        myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar, 2));
        myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));
        myCommand.Parameters.Add(new SqlParameter("@Contract", SqlDbType.NVarChar,1));
        myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
        String[] cols = {"LName","FName","Phone","Address","City","Zip"};
        for (int i=0; i<6; i++)
        {
            String colvalue = ((TextBox)E.Item.FindControl("edit_" + cols[i])).Text;
            // 檢查在所需欄位中是否有空值
            if (i<3 && colvalue == "")
            {
                Message.InnerHtml = "錯誤:“姓名”或“電話”不允許使用空值";
                Message.Style["color"] = "red";
                return;
            }
            myCommand.Parameters["@" + cols[i]].Value = colvalue;
        }



        myCommand.Parameters["@State"].Value = ((DropDownList)E.Item.FindControl("edit_State")).SelectedItem.ToString();



        if (((CheckBox)E.Item.FindControl("edit_Contract")).Checked == true)
            myCommand.Parameters["@Contract"].Value = "1";
        else
            myCommand.Parameters["@Contract"].Value = "0";
        myCommand.Connection.Open();
        try
        {
            myCommand.ExecuteNonQuery();
            Message.InnerHtml = "<b>已更新記錄</b><br>" + updateCmd;
            MyDataGrid.EditItemIndex = -1;
        }
        catch (SqlException e)
        {
            if (e.Number == 2627)
                Message.InnerHtml = "錯誤:已存在具有相同主鍵的記錄";
            else
                Message.InnerHtml = "錯誤:未能更新記錄,請確保正確填寫了欄位";
            Message.Style["color"] = "red";
        }
        myCommand.Connection.Close();
        BindGrid();
    }



    public void BindGrid()
    {
        SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
        DataSet ds = new DataSet();
        myCommand.Fill(ds, "Authors");
        MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
        MyDataGrid.DataBind();
    }



</script>



<body style="font: 10.5pt 宋體">
  <form runat="server">
    <h3><font face="宋體">更新具有模板列的資料行</font></h3>
    <span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/><p>
    <ASP:DataGrid id="MyDataGrid" runat="server"
      Width="800"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="Verdana"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      OnEditCommand="MyDataGrid_Edit"
      OnCancelCommand="MyDataGrid_Cancel"
      OnUpdateCommand="MyDataGrid_Update"
      DataKeyField="au_id"
      AutoGenerateColumns="false"
    >



      <Columns>
        <asp:EditCommandColumn EditText="編輯" CancelText="取消" UpdateText="更新"  ItemStyle-Wrap="false"/>
        <asp:BoundColumn HeaderText="au_id" SortExpression="au_id" ReadOnly="True" DataField="au_id" ItemStyle-Wrap="false"/>
        <asp:TemplateColumn HeaderText="au_lname" SortExpression="au_lname">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "au_lname") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_LName" Text="<%# DataBinder.Eval(Container.DataItem, "au_lname") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="au_fname" SortExpression="au_fname">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "au_fname") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_FName" Text="<%# DataBinder.Eval(Container.DataItem, "au_fname") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="phone" SortExpression="phone">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Phone" Text="<%# DataBinder.Eval(Container.DataItem, "phone") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="address" SortExpression="address">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "address") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Address" Text="<%# DataBinder.Eval(Container.DataItem, "address") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="city" SortExpression="city">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "city") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_City" Text="<%# DataBinder.Eval(Container.DataItem, "city") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="state" SortExpression="state">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "state") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:DropDownList runat="server" SelectedIndex="<%# GetStateIndex(DataBinder.Eval(Container.DataItem, "state").ToString()) %>" id="edit_State">
                  <asp:ListItem>CA</asp:ListItem>
                  <asp:ListItem>IN</asp:ListItem>
                  <asp:ListItem>KS</asp:ListItem>
                  <asp:ListItem>MD</asp:ListItem>
                  <asp:ListItem>MI</asp:ListItem>
                  <asp:ListItem>OR</asp:ListItem>
                  <asp:ListItem>TN</asp:ListItem>
                  <asp:ListItem>UT</asp:ListItem>
            </asp:DropDownList>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="zip" SortExpression="zip">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "zip") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" id="edit_Zip" Text="<%# DataBinder.Eval(Container.DataItem, "zip") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="contract" SortExpression="contract">
          <ItemTemplate>
            <asp:Label runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "contract", "{0}") %>"/>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:CheckBox runat="server" id="edit_Contract" Checked="<%# DataBinder.Eval(Container.DataItem, "contract") %>"/>
          </EditItemTemplate>
        </asp:TemplateColumn>
      </Columns>
    </ASP:DataGrid>
  </form>
</body>
</html>

相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。