您的位置:首页 > 其它

建立GridView Column

2015-07-05 11:18 302 查看
Instructions

Open Visual Studio. Click "File" and select "New Website."

Click "Visual C#," and then double-click "ASP.NET Website" to create a new website. The markup code for the default Web page appears in the center of the Visual Studio window.

Click the "Design" button at the bottom of the window to view the form designer.

Click "File" and select "Toolbox." Visual Studio will display the toolbox.

Scroll down and locate the "GridView" control. Double-click that control to place it on the form.

Press "F7." The source code window will open and display this code:

protected void Page_Load(object sender, EventArgs e)

{

}

This is the page load method. It runs when the Web page loads in a browser. Note the two bracket symbols below the first line of code.

Add this code between the two bracket symbols:

// Lines 1-5

System.Data.DataTable dataSourceTable = new System.Data.DataTable();

dataSourceTable.Columns.Add(new System.Data.DataColumn("Model", typeof(string)));

dataSourceTable.Columns.Add(new System.Data.DataColumn("Make", typeof(string)));

dataSourceTable.Columns.Add(new System.Data.DataColumn("Color", typeof(string)));

dataSourceTable.Rows.Add(originalColumnValues);

// Line 6

GridView1.AutoGenerateColumns = false;

// Line 7

GridView1.DataSource = dataSourceTable;

The first five lines create a data source containing three fields: Model, Make and Color. Line six sets the GridView's "AutoGenerateColumns" property to false. This prevents the GridView from generating columns automatically when you bind it to a data source. Line seven binds the GridView to the data source. At this point, the GridView displays no columns.

Add the following code below the code described in the previous step:

/ Lines 8-12

BoundField boundField = new BoundField();

boundField.DataField = "Make";

boundField.HeaderText = "Ford";

DataControlField dataControlField = boundField;

GridView1.Columns.Add(dataControlField);

// Lines 13 = 17

boundField = new BoundField();

boundField.DataField = "Model";

boundField.HeaderText = "Mustang";

dataControlField = boundField;

GridView1.Columns.Add(dataControlField);

// Line 18

GridView1.DataBind();

Lines eight through 12 create a bound field. This field references the data source's "Make" field. Line 10 assigns a value of "Ford" to the bound field. You can make this value anything you like. This is the value that appears in the new column. Line 12 adds the bound field to the GridView. Lines13 through 17 create another bound field. This bound field references the data source's "Model" field and sets its text value to "Mustang." Line 18 binds the GridView to the data source.

Press "F5" to run the application. Your Web browser will open and display the GridView and the columns you added.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: