| |

VerySource

 Forgot password?
 Register
Search
View: 597|Reply: 5

For a concise example of adding, deleting, and modifying code, use gridview!

[Copy link]

1

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-1-27 17:40:01
| Show all posts |Read mode
Changes and additions, preferably a separate interface!
Reply

Use magic Report

1

Threads

3

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

Post time: 2020-2-22 12:45:01
| Show all posts
I am making one, UP
Reply

Use magic Report

0

Threads

58

Posts

32.00

Credits

Newbie

Rank: 1

Credits
32.00

 China

Post time: 2020-2-22 16:00:01
| Show all posts
<% @ Page Language = "C #" ClassName = "Default_aspx"%>

<! DOCTYPE html PUBLIC "-/ W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat = "server">
    void CancelButton1_Click (object sender, EventArgs e)
    {

        GridView1.ShowFooter = false;

    }
    void AddButton1_Click (object sender, EventArgs e)
    {

        GridView1.ShowFooter = true;

    }

    void Button1_Click (object sender, EventArgs e)

    {
        
        TextBox customerID = GridView1.FooterRow.FindControl ("CustomerIDTextBox") as TextBox;

        TextBox companyName = GridView1.FooterRow.FindControl ("CompanyNameTextBox") as TextBox;

        DropDownList ContactTitle = GridView1.FooterRow.FindControl ("ContactTitleDropDownList") as DropDownList;

        SqlDataSource1.InsertParameters ["CustomerID"]. DefaultValue = customerID.Text;

        SqlDataSource1.InsertParameters ["CompanyName"]. DefaultValue = companyName.Text;

        SqlDataSource1.InsertParameters ["ContactTitle"]. DefaultValue = ContactTitle.SelectedValue;

        SqlDataSource1.Insert ();

    }
 

</ script>

<html xmlns = "http://www.w3.org/1999/xhtml">

<head id = "Head1" runat = "server">

    <title> Untitled Page </ title>

</ head>

<body>

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

    <div>
    <asp: Button ID = "AddButton1" runat = "Server" Text = "Add new Item" OnClick = "AddButton1_Click" />


    <asp: GridView ID = "GridView1" Runat = "server" DataSourceID = "SqlDataSource1" DataKeyNames = "CustomerID"

            AutoGenerateColumns = "False" ShowFooter = "True">

            <Columns>

                <asp: TemplateField>

                    <ItemTemplate>

                        <asp: Label ID = "CustomerIDLabel" Runat = "Server"> <% # Eval ("CustomerID")%> </ asp: Label>

                    </ ItemTemplate>

                    <FooterTemplate>

                        <asp: TextBox ID = "CustomerIDTextBox" Runat = "server"> </ asp: TextBox>

                    </ FooterTemplate>

                </ asp: TemplateField>

                <asp: TemplateField>

                    <ItemTemplate>

                        <asp: Label ID = "CompanyNameLabel" Runat = "Server"> <% # Eval ("CompanyName")%> </ asp: Label>

                    </ ItemTemplate>

                    <FooterTemplate>

                        <asp: TextBox ID = "CompanyNameTextBox" Runat = "server"> </ asp: TextBox>

                    </ FooterTemplate>

                </ asp: TemplateField>

                <asp: TemplateField>

                    <FooterTemplate>

                        <asp: DropDownList ID = "ContactTitleDropDownList" Runat = "server" DataSourceID = "SqlDataSource2" DataTextField = "ContactTitle" DataValueField = "ContactTitle">

                        </ asp: DropDownList>

                        <asp: SqlDataSource ID = "SqlDataSource2" Runat = "server" SelectCommand = "SELECT DISTINCT [ContactTitle] FROM [Customers]"

                            ConnectionString = "server = localhost; uid = sa; password = xxx; database = northwind">

                        </ asp: SqlDataSource>

                        <asp: Button ID = "Button1" Runat = "server" Text = "Add" OnClick = "Button1_Click" />
  <asp: Button ID = "CancelButton1" Runat = "server" Text = "Cancel" OnClick = "CancelButton1_Click" />

                    </ FooterTemplate>

                    <ItemTemplate>

                        <asp: DropDownList ID = "ContactTitleDropDown" SelectedValue = '<% # Bind ("ContactTitle")%>' Runat = "Server" DataSourceID = "SqlDataSource3" DataTextField = "ContactTitle" DataValueField = "ContactTitle"> </ asp: DropDownList >

                        <asp: SqlDataSource ID = "SqlDataSource3" Runat = "server" SelectCommand = "SELECT DISTINCT [ContactTitle] FROM [Customers]"

                            ConnectionString = "server = localhost; uid = sa; password = xxx; database = northwind" EnableCaching = "True">

                        </ asp: SqlDataSource>

                    </ ItemTemplate>

                </ asp: TemplateField>

            </ Columns>

        </ asp: GridView>

        <asp: SqlDataSource ID = "SqlDataSource1" Runat = "server"

            InsertCommand = "INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)"

            SelectCommand = "SELECT [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]"

            ConnectionString = "server = localhost; uid = sa; password = xxxxx; database = northwind">

            <DeleteParameters>

                <asp: Parameter Type = "String" Name = "CustomerID"> </ asp: Parameter>

            </ DeleteParameters>

            <UpdateParameters>

                <asp: Parameter Type = "String" Name = "CompanyName"> </ asp: Parameter>

                <asp: Parameter Type = "String" Name = "ContactTitle"> </ asp: Parameter>

                <asp: Parameter Type = "String" Name = "CustomerID"> </ asp: Parameter>

            </ UpdateParameters>

            <InsertParameters>

                <asp: Parameter Type = "String" Name = "CustomerID"> </ asp: Parameter>

                <asp: Parameter Type = "String" Name = "CompanyName"> </ asp: Parameter>

                <asp: Parameter Type = "String" Name = "ContactTitle"> </ asp: Parameter>

            </ InsertParameters>

        </ asp: SqlDataSource>

    </ div>

    </ form>

</ body>

</ html>
Reply

Use magic Report

0

Threads

3

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-2-22 22:00:01
| Show all posts
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "GridView_2.aspx.cs" Inherits = "GridView_2"%>
<! 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">
<head runat = "server">
    <title> GridView's online editing capabilities </ title>
</ head>
<body>
    <form id = "form1" runat = "server">
    <div>
           <asp: GridView ID = "GridView1" DataKeyNames = "id" runat = "server" AllowPaging = "True" AutoGenerateColumns = "False"
            PageSize = "4" OnPageIndexChanging = "GridView1_PageIndexChanging" Width = "100%" OnRowCancelingEdit = "GridView1_RowCancelingEdit" OnRowEditing = "GridView1_RowEditing" OnRowUpdating = "GridView1_RowUpdating" OnRowDeleting = "GridView1_RowDeleting">
            <Columns>
                <asp: BoundField DataField = "id" HeaderText = "ID number" ReadOnly = "true" />
                <asp: BoundField DataField = "name" HeaderText = "name" ReadOnly = "true" />
                <asp: ImageField DataImageUrlField = "face" HeaderText = "Avatar" ReadOnly = "true" />
                <asp: BoundField DataField = "tel" HeaderText = "Phone" />
                <asp: CommandField HeaderText = "Update" ShowEditButton = "True" />
                <asp: CommandField HeaderText = "Delete" ShowDeleteButton = "True" />
            </ Columns>
        </ asp: GridView>
    </ div>
    </ form>
</ body>
</ html>
Note that when we declared the GridView control above, OnRowCancelingEdit = "GridView1_RowCancelingEdit" specifies the name of the event that cancels editing, OnRowEditing = "GridView1_RowEditing" indicates the name of the event that activates editing, OnRowUpdating = "GridView1_RowUpdating" indicates the name of the event that confirms the update, OnRowDeleting = "GridView1_RowDeleting" indicates the name of the event that performed the deletion. By default, all columns of the GridView in the edit state are editable. If we are not allowed to edit a column, specify ReadOnly = "true" for a column. Here, we assume that only the phone column is allowed to be edited, and the other columns are not allowed to be edited.
The code of GridView_2.aspx.cs is as follows.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridView_2: System.Web.UI.Page
{
    protected void Page_Load (object sender, EventArgs e)
    {
        if (! Page.IsPostBack)
        {
            // Save the generated data table in the Session,
            Session ["DataBase"] = CreatDataBase ();
            // Call the binding method
            GridViewDataBind ();
        }

    }
    // data binding
    protected void GridViewDataBind ()
    {
        DataTable dt = (DataTable) Session ["DataBase"];
        // Specify the data source of the GridView1 control
        this.GridView1.DataSource = dt;
        // Call the DataBind method of the GridView1 control
        this.GridView1.DataBind ();

    }
    // Generate a data table, which is the data source of the data-bound control
    protected DataTable CreatDataBase ()
    {
        DataTable dt = new DataTable ();
        DataColumn dc = new DataColumn ("id", typeof (int));
        dt.Columns.Add (dc);
        dc = new DataColumn ("name", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("tel", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("email", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("face", typeof (string));
        dt.Columns.Add (dc);
        int i = 1;
        DataRow dr;
        for (i = 1; i <10; i ++)
        {
            dr = dt.NewRow ();
            dr ["id"] = i;
            dr ["name"] = "Name." + i.ToString () + ".";
            dr ["tel"] = "+ 86-755-8839-3207";
            dr ["email"] = "Email_" + i.ToString () + "@ hotmail.com";
            dr ["face"] = "./images/" + i.ToString () + ".gif";
            dt.Rows.Add (dr);
        }
        return dt;
    }
    // GridView control page turning event
    protected void GridView1_PageIndexChanging (object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        GridViewDataBind ();
    }
    protected void GridView1_RowEditing (object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;
        GridViewDataBind ();
    }
    protected void GridView1_RowCancelingEdit (object sender, GridViewCancelEditEventArgs e)
    {
        this.GridView1.EditIndex = -1;
        GridViewDataBind ();
    }
    protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e)
    {
        // The current operation line, Index = e.RowIndex of the current operation line
        GridViewRow dvr = GridView1.Rows [e.RowIndex];
        
        // Get updated cells
        TableCell tc = dvr.Cells [3];
        // The TextBox control in the cell.
        TextBox tb = (TextBox) tc.Controls [0];
        // Get the Txext of the TextBox control, which is the updated value
        string NewValue = tb.Text;
        // Get the ID key value in the data table
        string id = dvr.Cells [0] .Text;
        / * -----------------------------------
         * The method of obtaining id above is equivalent to string id = GridView1.DataKeys [e.RowIndex] .Value.ToString ();
         * Although the above method is tedious, this method can get the content of other columns,
         * You can also get the properties of other controls in each cell, this is especially useful in the responsible GridView table
         * ------------------------------------------------- -
         * * /
        DataTable dt = (DataTable) Session ["DataBase"];
        foreach (DataRow dr in dt.Rows)
        {
            // Find the original data and update
            if (dr ["id"]. ToString () == id)
            {
                dr ["tel"] = NewValue;
                break;
            }
        }
        // Save the updated data to Seesion. In practice, we will save it to the database.
        Session ["DataBase"] = dt;
        // Restore edit status
        this.GridView1.EditIndex = -1;
        // Refresh the data
        GridViewDataBind ();
    }

    protected void GridView1_RowDeleting (object sender, GridViewDeleteEventArgs e)
    {
        string id = GridView1.DataKeys [e.RowIndex] .Value.ToString ();
        DataTable dt = (DataTable) Session ["DataBase"];
        foreach (DataRow dr in dt.Rows)
        {
            // Find the original data and update
            if (dr ["id"]. ToString () == id)
            {
                dt.Rows.Remove (dr);
                break;
            }
        }
        // Save the updated data to Seesion. In practice, we will save it to the database.
        Session ["DataBase"] = dt;
        // Refresh the data
        GridViewDataBind ();
    }
}
Reply

Use magic Report

0

Threads

3

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-2-22 23:45:02
| Show all posts
3.3.3.3 Dynamic Sorting Function of GridView Control
The GridView control provides a sorting function, which specifies sorting fields before data binding. Although this sort can meet some needs, more often we need a dynamic sort. AllowPaging = "True" in the configuration properties of the GridView control indicates that sorting is allowed. If you specify which column is a sort column, you only need to add the configuration property SortExpression. Examples are as follows.
Create a new page GridView_3.aspx, and add a GridView control, the code is as follows.
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "GridView_3.aspx.cs" Inherits = "GridView_3"%>
<! 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">
<head runat = "server">
    <title> GridView sorting function </ title>
</ head>
<body>
    <form id = "form1" runat = "server">
    <div>
     <asp: GridView ID = "GridView1" runat = "server" AllowPaging = "True" AutoGenerateColumns = "False"
            PageSize = "4" OnPageIndexChanging = "GridView1_PageIndexChanging" Width = "100%" AllowSorting = "True" OnSorting = "GridView1_Sorting">
            <Columns>
                <asp: BoundField DataField = "id" HeaderText = "ID number" ReadOnly = "True" SortExpression = "id" />
                <asp: BoundField DataField = "name" HeaderText = "name" ReadOnly = "True" SortExpression = "name" />
                <asp: ImageField DataImageUrlField = "face" HeaderText = "avatar" ReadOnly = "True" />
                <asp: BoundField DataField = "tel" HeaderText = "Phone" SortExpression = "tel" />
            </ Columns>
</ asp: GridView>
    </ div>
    </ form>
</ body>
</ html>
Note that OnSorting = "GridView1_Sorting" means that when a sort event occurs, that event is processed.
GridView_3.aspx.cs code is as follows.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridView_3: System.Web.UI.Page
{
    protected void Page_Load (object sender, EventArgs e)
    {
        if (! Page.IsPostBack)
        {
            // Save the generated data table in the Session,
            Session ["DataBase"] = CreatDataBase ();
            // The default sort field
            ViewState ["Sort"] = "id";
            // default collation
            ViewState ["Direction"] = "ASC";
            // Call the binding method
            GridViewDataBind ();
        }

    }
    // data binding
    protected void GridViewDataBind ()
    {
        // Get the data table
        DataTable dt = (DataTable) Session ["DataBase"];
        // create data view
        DataView dv = dt.DefaultView;
        // Specify the collation of the view
        dv.Sort = ViewState ["Sort"]. ToString () + "" + ViewState ["Direction"]. ToString ();
        // Specify the data source of the GridView control
        this.GridView1.DataSource = dv;
        this.GridView1.DataBind ();

    }
    // Generate a data table, which is the data source of the data-bound control
    protected DataTable CreatDataBase ()
    {
        DataTable dt = new DataTable ();
        DataColumn dc = new DataColumn ("id", typeof (int));
        dt.Columns.Add (dc);
        dc = new DataColumn ("name", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("tel", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("email", typeof (string));
        dt.Columns.Add (dc);
        dc = new DataColumn ("face", typeof (string));
        dt.Columns.Add (dc);
        int i = 1;
        DataRow dr;

        for (i = 1; i <10; i ++)
        {
            dr = dt.NewRow ();
            dr ["id"] = i;
            dr ["name"] = "Name." + i.ToString () + ".";
            dr ["tel"] = "+ 86-755-8839-3207";
            dr ["email"] = "Email_" + i.ToString () + "@ hotmail.com";
            dr ["face"] = "./images/" + i.ToString () + ".gif";
            dt.Rows.Add (dr);
        }
        return dt;
    }
    // GridView control page turning event
    protected void GridView1_PageIndexChanging (object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        GridViewDataBind ();
    }
    protected void GridView1_Sorting (object sender, GridViewSortEventArgs e)
    {
        // Dynamically change the collation according to the current collation
        if (ViewState ["Direction"]. ToString () == "ASC")
            ViewState ["Direction"] = "DESC";
        else
            ViewState ["Direction"] = "ASC";
        // Get the sort field
       ViewState ["Sort"] = e.SortExpression;
     GridViewDataBind ();
    }
    protected void GridView1_DataBound (object sender, EventArgs e)
    {
        // Get the header row.
        GridViewRow headerRow = GridView1.HeaderRow;

        // Get the footer row.
        GridViewRow footerRow = GridView1.FooterRow;

        // Set the font color of the header and footer rows
        // based on the sort direction.
        switch (this.GridView1.SortDirection)
        {
            case SortDirection.Ascending:
                headerRow.ForeColor = System.Drawing.Color.Green;
                footerRow.ForeColor = System.Drawing.Color.Green;
                break;
            case SortDirection.Descending:
                headerRow.ForeColor = System.Drawing.Color.Red;
                footerRow.ForeColor = System.Drawing.Color.Red;
                break;
            default:
                headerRow.ForeColor = System.Drawing.Color.Black;
                footerRow.ForeColor = System.Drawing.Color.Black;
                break;
        }
        // Display the sort order in the footer row.
        footerRow.Cells [0] .Text = "Sort Order =" + GridView1.SortDirection.ToString ();
      

    }
}
Reply

Use magic Report

0

Threads

3

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-2-23 06:15:02
| Show all posts
Above two cases, copy and paste can be used!
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list