ASP.NET 2.0 GridView Restern DROPDOWNLIST

xiaoxiao2021-04-03  227

In ASP.NET 2.0, in a GridView, you can nested into a DropDownList, which is very easy, and here is,

In each DropDownList, it is bound to be different. For example, in the Northwind database, you can display it with GridView.

Each Category category, and each line of Category categories can have a DropDonwlist drop-down box in the form of this category listing all

Product. The method of implementation is described below

The first is the code of the page part

in the CodeBehind section, protected void page_load (object sender, eventargs e) {if (! page.ispostback) {

// this is because table [1] contains categories

GridView1.datasource = getDataSet (). Tables [1];

GridView1.databind ();

}

} Private dataset getdata set () {

String query = @ "SELECT P.CategoryID, P.ProductId, P.ProductName from Products P

Select C.categoryId, C.categoryName from Categories C ";

String Connectionstring = "Server = localhost; database = northwind; user ID = sa; password = 123456";

SqlConnection MyConnection = New SqlConnection (Connectionstring);

SqlDataAdapter ad = new sqldataadapter (query, myconnection);

DataSet DS = New Dataset ();

Ad.fill (DS);

Return DS;

} In the above code, first we return to GridView through a typical DataSet, note that there are two sentences in the SQL statement, the first sentence is return product, the second sentence is to return all categories category, while tied When GridView, we use GridView1.DataSource = getDataSet (). Tables [1]; this can be written in row_databound event code, the following protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e) {DataTable myTable = new DataTable (); DataColumn productIDColumn = new DataColumn ( "ProductID");

Datacolumn ProductnameColumn = New Datacolumn ("ProductName");

MyTable.Columns.Add (ProductidColumn);

MyTable.Columns.Add (ProductNameColumn);

DataSet DS = New Dataset ();

DS = getDataSet ();

INT categoryId = 0;

String expression = string.empty;

IF (E.Row.RowType == DatacontrolRowType.DataRow) {

CategoryId = int32.Parse (E.Row.cells [0] .text);

Expression = "categoryid =" categoryId;

DropDownList DDL = (DropDownList) E.Row.FindControl ("DropDownList1");

DataRow [] rows = ds.tables [0] .select (expression);

Foreach (Datarow Row In Rows) {

DataRow newrow = myTable.newrow ();

NEWROW ["ProductID"] = row ["productID"];

NEWROW ["ProductName"] = row ["productname"];

MyTable.Rows.Add (newrow);

}

DDL.DataSource = MyTable;

DDL.DATATEXTFIELD = "ProductName";

DDL.DataValuefield = "productID";

DDL.DATABIND ();

}

} The principle here is as follows: First, we have established a DataTable, including the productID, the productname column, then bind it with the GridView, then use categoryid = int32.parse (E.Row.cells [0] .text) ;

转载请注明原文地址:https://www.9cbs.com/read-131582.html

New Post(0)