Feel the convenience of DataGrid to data operation (6)

xiaoxiao2021-03-06  65

Section 6: Sort by column

When we use data, we often sort the data, then what do DataGrid provided us in this respect? Is it easy to achieve like other functions? I just experienced it, the answer is: It is really simple.

First, I want to set the property of DataGrid, allowing it to sort, the property name is: AllowSorting, the default is false, we set to True, this time, if you compile, you will find the title of each column plus super link. However, this time, you click on these titles and there is nothing to respond because you have not written code for these events. We creating an event onsortcommand () - Click the event that occurs during the column title.

You can write directly to DataGrid to resolink data directly in this function, I, here, I still want to transform the function bindgrid () that I have been using in front.

First, I want to add a parameter to tell the procedure, which one should be sorted, my function programmed BindGrid (String Sortfield)

Then, I want to add a DataView to sort the data. Let's take a detailed code, pay attention, change the part, I am marked with red:

Public void bindgrid (String Strsortfield)

{

String selectcmd = "SELECT Decoction AS ID, Name AS Name, company AS Company from Sheet1 $";

SqldataAdapter mycomm = new sqldataadapter (selectcmd, cn);

DataSet DS = New Dataset ();

Mycomm.fill (DS, "Sheet1 $");

DataView Source = DS.TABLES ["Sheet1 $"]. DefaultView;

Source.sort = strsortfield;

DataGrid1.datasource = Source; /// DS.Tables ["Sheet1 $"]. Defaultview; // It turned out to give DS data directly to DataSource

DataGrid1.databind ();

}

We apply this function in the onsrotcommand event:

Private void DataGrid1_sortcommand (Object Source, System.Web.ui.WebControls.DataGridsortCommandeventArgs E)

{

// Parameter E is used to pass the column name

Bindgrid (E.Sortexpression);

}

If we are sorted in reverse or sequentially, we can add "ASC" or "DESC", such as:

Private void DataGrid1_sortcommand (Object Source, System.Web.ui.WebControls.DataGridsortCommandeventArgs E)

{

// Parameter E is used to pass the column name

Bindgrid (E.Sortexpression "DESC");

}

We often have such a need, click on a list of titles, order sequential, then click on a list title, ink, order, the following code to complete this:

Private void DataGrid1_sortcommand (Object Source, System.Web.ui.WebControls.DataGridsortCommandEventArgs E) {

DataGrid1.currentpageIndex = 0;

IF (label1.text == "1") // In the web program, I like to use controls to save global variables.

{

Bindgrid (E.Sortexpression "DESC");

Label1.text = "0";

}

Else

{

Bindgrid (E.Sortexpression "ASC");

Label1.text = "1";

}

}

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

New Post(0)