ASP.NET Tutorial/ASP.net Controls/DataGrid

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

asp:EditCommandColumn in asp:DataGrid (VB.net)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
   sub Page_Load(Sender as Object, e as EventArgs) 
      dim myConnection as new OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
      dim myCommand as new OleDbDataAdapter _
         ("select * from employee", myConnection)
      dim ds as DataSet = new DataSet()
      myCommand.Fill(ds, "employee")
      DataGrid1.DataSource = ds
      DataGrid1.DataMember = "employee"
      DataBind()
   end sub
   
   sub DataGrid1_Edit(Sender as Object, e as DataGridCommandEventArgs)
      DataGrid1.EditItemIndex = e.Item.ItemIndex
      DataGrid1.DataBind()
   end sub
   sub DataGrid1_Update(Sender as Object, e as DataGridCommandEventArgs)
      DataGrid1.DataBind()
   end sub
   sub DataGrid1_Cancel(Sender as Object, e as DataGridCommandEventArgs)
      DataGrid1.EditItemIndex = -1
      DataGrid1.DataBind()
   end sub
   
   sub DataGrid1_SortCommand(Sender as Object, e as DataGridSortCommandEventArgs)
      DataGrid1.DataBind()
   End Sub
   sub DataGrid1_PageIndexChanged(Sender as Object, e as DataGridPageChangedEventArgs)
      DataGrid1.CurrentPageIndex = e.NewPageIndex
      DataGrid1.DataBind()
   end sub

</script>
<body>
   <form runat="server">
      <asp:DataGrid id="DataGrid1" runat="server"
        BorderColor="black"
        GridLines="Vertical"
        cellpadding="4"
        cellspacing="0"
        width="450"
        Font-NameFont-Names="Arial"
        Font-Size="8pt"
        ShowFooter="True"
        HeaderStyle-BackColor="#cccc99"
        FooterStyle-BackColor="#cccc99"
        ItemStyle-BackColor="#ffffff"
        AlternatingItemStyle-Backcolor="#cccccc"
        AutoGenerateColumns="false"
        AllowSorting=true
        OnEditCommand="DataGrid1_Edit"
        OnCancelCommand="DataGrid1_Cancel"
        OnUpdateCommand="DataGrid1_Update"
        AllowPaging="True"
        PageSize=2
        PagerStyle-Mode=NumericPages
        PagerStyle-PageButtonCount = 2
        OnPageIndexChanged="DataGrid1_PageIndexChanged" >
  
        <Columns>
  
              <asp:TemplateColumn HeaderText="Name">
                    <ItemTemplate>
                          <asp:Label id="Name" runat="server"
                                Text="<%# Container.DataItem("FirstName")& _
                                " " & Container.DataItem("LastName") %>"/>
                    </ItemTemplate>
               </asp:TemplateColumn>
  
              <asp:BoundColumn HeaderText="ID" DataField="ID"/>
  
              <asp:EditCommandColumn
                 EditText="Edit"
                 CancelText="Cancel"
                 UpdateText="Update"
                 ItemStyle-Wrap="false"
                 HeaderText="Edit" />
        </Columns>
  </asp:DataGrid>
   </form>
   
</body>
</html>


Bind data of directories to asp:DataGrid (VB.net)

<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
   
   void Page_Load(Object Sender, EventArgs e) {
      DirectoryInfo dir = new DirectoryInfo(Server.MapPath("."));
      DataGrid2.DataSource = dir.GetDirectories();
      DataGrid2.DataBind();
      
   }
</script>
<html><body>
   <b>Directory information</b><br>
   <asp:DataGrid id="DataGrid2" runat="server" 
      AlternatingItemStyle-Backcolor="#cccccc"
      AutogenerateColumns="true" />
</body></html>


Bind file information to asp:DataGrid (VB.net)

<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
   
   void Page_Load(Object Sender, EventArgs e) {
      DirectoryInfo dir = new DirectoryInfo(Server.MapPath("."));
      DataGrid1.DataSource = dir.GetFiles("*.*");
      DataGrid1.DataBind();
      
   }
</script>
<html><body>
   <b>File information</b><br>
   <asp:DataGrid id="DataGrid1" runat="server" 
      AlternatingItemStyle-Backcolor="#cccccc"
      AutogenerateColumns="true" />
   
</body></html>


Binding DataReader to DataGrid

<%@ Page Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">
    SqlDataReader myReader;
    
    void Page_Load(object sender, EventArgs e)
    {
       string ConnectionString = Convert.ToString(ConfigurationSettings.AppSettings["MSDEConnectString"]);
    
       SqlConnection myConnection = new SqlConnection(ConnectionString);
       SqlCommand myCommand = new SqlCommand();
       myCommand.Connection = myConnection;
    
       try {
          myConnection.Open();
          if (!(Page.IsPostBack)) {
             myCommand.rumandText = "SELECT PublisherID, PublisherName FROM Publisher";
             myReader = myCommand.ExecuteReader();
             ListBox1.DataBind();
             myReader.Close();
          } else {
             myCommand.rumandText = "SELECT * FROM Book WHERE BookPublisherID=" + ListBox1.SelectedItem.Value;
             myReader = myCommand.ExecuteReader();
             DataGrid1.DataSource = myReader;
             DataGrid1.DataBind();
             myReader.Close();
          }
       } catch (Exception ex) {
          throw (ex);
       } finally {
          myConnection.Close();
       }
    }
</script>
<html>
<head>
</head>
<body>
    <form runat="server">
        <h2>A RadioButtonList 
        </h2>
            <asp:RadioButtonList id="RadioButtonList1" runat="server" AutoPostBack="True" DataValueField="PublisherID" DataTextField="PublisherName" DataSource="<%# myReader %>"></asp:RadioButtonList>
        <h2>A DropDownList 
        </h2>
            <asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True" DataValueField="PublisherID" DataTextField="PublisherName" DataSource="<%# myReader %>"></asp:DropDownList>
        <h2>A ListBox 
        </h2>
            <asp:ListBox id="ListBox1" runat="server" AutoPostBack="True" DataValueField="PublisherID" DataTextField="PublisherName" DataSource="<%# myReader %>" Rows="5"></asp:ListBox>
            <asp:Label id="Label1" runat="server"></asp:Label>
            <asp:DataGrid id="DataGrid1" runat="server" HorizontalAlign="Justify" BorderColor="#CC9966" BackColor="White" CellPadding="4" BorderWidth="1px" BorderStyle="None">
                <FooterStyle forecolor="#330099" backcolor="#FFFFCC"></FooterStyle>
                <HeaderStyle font-bold="True" forecolor="#FFFFCC" backcolor="#990000"></HeaderStyle>
                <PagerStyle horizontalalign="Center" forecolor="#330099" backcolor="#FFFFCC"></PagerStyle>
                <SelectedItemStyle font-bold="True" forecolor="#663399" backcolor="#FFCC66"></SelectedItemStyle>
                <ItemStyle forecolor="#330099" backcolor="White"></ItemStyle>
            </asp:DataGrid>
    </form>
</body>
</html>


File: Web.config
<configuration>
    <appSettings>
        <add key="MSDEConnectString" value="server=(local)\YourDatabase;database=Books;uid=YourID;pwd=letmein;" />
    </appSettings>
</configuration>


DataGrid Data Binding

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
   "declare connection
   dim Conn as new OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
   
   
   sub GetData(Sender as Object, e as EventArgs) 
      dim objCmd as OleDbCommand = new OleDbCommand _
         ("select * from employee where ID = @ID", Conn)
      dim objReader as OleDbDataReader
      
      dim objParam as OleDbParameter
      objParam = objCmd.Parameters.Add("@ID", OleDbType.Integer)
      objParam.Direction = ParameterDirection.Input
      objParam.Value = tbID.Text
           
      try
         objCmd.Connection.Open()
         objReader = objCmd.ExecuteReader
         
         dgData.DataSource = objReader
         dgData.DataBind()
       
         objReader.Close
         objCmd.Connection.Close()
      catch objEx as FormatException
         lblMessage.Text = objEx.Message
      catch objEx as OleDbException
         lblMessage.Text = "Database error!"
      catch objEx as Exception
         lblMessage.Text = "Unknown error!"
      end try      
   end sub
</script>
<html><body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server"
         maintainstate=false /><br>
      Enter an ID: <asp:TextBox id="tbID" runat="server"
         AutoPostBack=True
         OnTextChanged=GetData />
      <asp:DataGrid id="dgData" runat="server" 
         BorderColor="black" 
         GridLines="Vertical" 
         width="100%"
         Font-Name="Arial" 
         Font-Size="8pt" 
         HeaderStyle-BackColor="#cccc99"
         ItemStyle-BackColor="#ffffff"
         AlternatingItemStyle-Backcolor="#cccccc"
         AutoGenerateColumns="true" />
   </form>
</body></html>


Use asp:DataGrid to edit data in an Access table (VB.net)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
   sub Page_Load(Sender as Object, e as EventArgs) 
      dim myConnection as new OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
      dim myCommand as new OleDbDataAdapter("select * from employee", myConnection)
      dim ds as DataSet = new DataSet()
      myCommand.Fill(ds, "employee")
      DataGrid1.DataSource = ds.Tables("employee").DefaultView
      DataBind()
   end sub
   
   sub DataGrid1_ItemCommand(obj as object, e as _
      DataGridCommandEventArgs)
      DataGrid1.SelectedIndex = e.Item.ItemIndex
      DataBind()
   end sub
</script>
<body>
   <form runat="server">
      <asp:DataGrid id="DataGrid1" runat="server"
        BorderColor="black"
        GridLines="Vertical"
        cellpadding="4"
        cellspacing="0"
        width="450"
        Font-NameFont-Names="Arial"
        Font-Size="8pt"
        ShowFooter="True"
        HeaderStyle-BackColor="#cccc99"
        FooterStyle-BackColor="#cccc99"
        ItemStyle-BackColor="#ffffff"
        AlternatingItemStyle-Backcolor="#cccccc"
        AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateColumn HeaderText="Name">
                  <ItemTemplate>
                        <asp:Label id="Name" runat="server"
                              Text="<%# Container.DataItem("FirstName")& _
                               " " & Container.DataItem("LastName") %>"/>
                  </ItemTemplate>
            </asp:TemplateColumn>
  
            <asp:BoundColumn HeaderText="ID" DataField="ID"/>
  
            <asp:HyperlinkColumn HeaderText="Edit" text="Edit" NavigateURL="edit.aspx"/>
  
            <asp:ButtonColumn HeaderText="Delete?" text="X" CommandName="delete" ButtonType="PushButton"/>
  
        </Columns>
  </asp:DataGrid>
   </form>
   
</body>
</html>


Use asp:HyperlinkColumn and asp:ButtonColumn in asp:DataGrid (VB.net)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
   sub Page_Load(Sender as Object, e as EventArgs) 
      dim myConnection as new OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
      dim myCommand as new OleDbDataAdapter("select * from employee", myConnection)
      dim ds as DataSet = new DataSet()
      myCommand.Fill(ds, "employee")
      DataGrid1.DataSource = ds.Tables("employee").DefaultView
      DataBind()
   end sub
   
   sub DataGrid1_ItemCommand(obj as object, e as _
      DataGridCommandEventArgs)
      DataGrid1.SelectedIndex = e.Item.ItemIndex
      DataBind()
   end sub
</script>
<body>
   <form runat="server">
      <asp:DataGrid id="DataGrid1" runat="server"
        BorderColor="black"
        GridLines="Vertical"
        cellpadding="4"
        cellspacing="0"
        width="450"
        Font-NameFont-Names="Arial"
        Font-Size="8pt"
        ShowFooter="True"
        HeaderStyle-BackColor="#cccc99"
        FooterStyle-BackColor="#cccc99"
        ItemStyle-BackColor="#ffffff"
        AlternatingItemStyle-Backcolor="#cccccc"
        AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateColumn HeaderText="Name">
                  <ItemTemplate>
                        <asp:Label id="Name" runat="server"
                              Text="<%# Container.DataItem("FirstName")& _
                               " " & Container.DataItem("LastName") %>"/>
                  </ItemTemplate>
            </asp:TemplateColumn>
  
            <asp:BoundColumn HeaderText="ID" DataField="ID"/>
  
            <asp:HyperlinkColumn HeaderText="Edit" text="Edit" NavigateURL="edit.aspx"/>
  
            <asp:ButtonColumn HeaderText="Delete?" text="X" CommandName="delete" ButtonType="PushButton"/>
  
        </Columns>
  </asp:DataGrid>
   </form>
   
</body>
</html>