As a person who just contact ASP.NET, DataGrid can provide us with those convenience, always I want to know early. These two days I happened to modify the previous ASP app, so I learned to learn DataGrid, I realized it, I really brought a lot of convenience, summed up, write it out to give a beginner like me. .
Part 1: Display all data in the data table with DataGrid
One purpose we use DataGrid is to use it to display data. Let's first put a DataGrid on the page, such as DataGrid1, next, we want to define a global database link on the page, you can create a "SQLConnection" from the VS.Net2003 toolbox, such as "MyConn", When the system will be regenerated into WebForm, you can initialize it, you can also initialize it in the page_load event:
Private Void Page_Load (Object Sender, System.EventArgs E)
{
IF (! ispostback)
{
THISMYCONN.CONNECTIONSTRING = "Workstation ID = TEST; packet size = 4096; integrated security = SSPI; data source = a" "PPServer; persist security info = false; initial catalog = oa";
}
// For convenience, I created a function to populate data to DataGrid
Bindgrid ();
}
Create a function bindgrid ();
Public void bindgrid ()
{
// Create an adapter
SqldataAdapter myadp = new sqldataadapter ("Select * from myTable", myconn;
// Create a dataset
DataSet DS = New Dataset ();
/ / Then populate the data in the database to the data set by the adapter
myadp.fill (DS, "MyTable"); // myTable is the name of the database table
// Use the data set as the data source of DataGrid
DataGrid1.datasource = DS.TABLES ["MyTable"]. DefaultView;
// Bind data, the data is displayed
DataGrid1.databind ();
}
OK, it is displayed!
The program is really much less than the original ASP, and it is so much fast.
Section 2: Customize the appearance of DataGrid
In the previous article, I prelimated the convenience of DataGrid to me, but if it is the form of the program drawing the program, we can make a flexible control form of expression, so DataGrid can customize it. Manifestations. Answer, I know that it is ok, the key is whether it is coming than my own code "painting".
Based on past experience, I know that these operations can be completed from the attributes of DataGrid.
1. Select the columns to display:
In the default, our columns we displayed in the DataGrid are the columns we queried when we execute SQL query statements. What do you mean? If we use select * from myTable, all columns will be displayed. If we use SELECT FIELD1, Field2 from MyTable, only two columns are displayed. So, in the DataGrid, choose the column you want to display, the simplest method is not to modify the properties, but is done by modifying the SQL query statement. There is also a small problem, that is, when we design the database, the name of the field is often in English. However, we have to use Chinese in DataGrid, we need to give each field alias in the SELECT statement. For example: Select Name As Name, CardID AS INGA from MyTable.
Sometimes, we are not convenient to use this way to choose the columns we want to display, then we use the property generator to set it.
In the design view, select the DataGrid, then "Property Window" will have a link to the "Properties Builder", click this link (or find the columns attribute), pop up a dialog box, we can pass this dialog To set the columns to choose:
First, we remove the hook in front of the "automatically created in runtime", which is no longer automatically created, and only the column you bind.
Click "Column" on the left, and the "Bind Column" "button column", etc., here we have to choose "Bind Column". Add a binding column, then fill in the "Header Text" and other items. The header text refers to the page title, "Data Field" fills in the name of the field you want to display. Then, you have to bind a few fields, choose a few bindings.
2, modify the style of DataGrid
The table of DataGrid draws by default is difficult, so I need to customize it. Checking the DataGrid, the bottom of the Properties window will appear link, click this link, you will pop up a dialog that allows you to select the format, select the format you wish.
I don't know how you think, anyway, I think there are two formats in this format, and it is also in line with the company's design specification, so I tend to use these formats. If you are still not satisfied, then you need to customize yourself. It is also very simple to customize yourself, that is, you can modify the properties of the "Style" class. In addition, you can also complete the modification of the style properties through the property generator. For example, you don't want your form back, then you go to the property generator, select "Format", then select "Item on the right, put the" unit grid text in each sub-text " The hook is OK.
Section III: Fast Page
In the second quarter, I realized that DataGrid's fast and convenient in custom appearance, this section, I learned to patch data quickly.
When we query the database, we often use a page to display all the data, but the data is displayed. Remember in the ASP, we write a page of page very troublesome, when I learned to use DataGrid to render data, I am excited, because it is as simple as data sheets.
Still open attribute generators (or modify the properties of the "Page" class), this time you know you want to choose the "paging" branch on the left. On the right, select "Allow Pack", then set the number of strips, page navigation bars, and so on. Do you think this is ok, I think so, I think so, but when I run this program, I found that there is no reaction after clicking the navigation bar. Because we have to write a few code to complete this operation. We selected the DataGrid, then select the event tab in the tab at the top of the property window (because we want to create a flip event ", find the" pageIndexchanged "event, write the following code:
Private void DataGrid1_pageIndexchanged (Object Source, System.Web.ui.WebControls.DataGridPageChangeDeventargs E)
{
DataGrid1.currentPageIndex = E.NewpageIndex;
Bindgrid ();
}
Oh, good "long" code!
explain:
DataGrid1 It has a property called CurrentPageInde to specify the shortest page now. The "E" parameter of "PageIndexchanged" event is, you can tell Dagtagrid1 which page should be displayed.
Bindgrid () is the function I used to bind the data in the first quarter. Don't write it again, check the article in the first quarter.
It's so simple, don't believe, you try.
Section IV: Edit data
I don't know how to modify the database record in the ASP program. Anyway, my approach is to make a list, list all records, then add a hyperlink, then add a hyperlink, then after the user clicks the hyperlink, Forward the page to a new editing page. At that time, I think about editing the Excel form, modify the field I want to modify in my own list. Then, DataGrid provides me with such functions. In DataGrid, you can add a "editing" operation column through the attribute generator in front of the data list, that is, the front (each line) of each record will add a "editing" hyperlink, click this hyperlink, this One way will become editable, each field will become a text box, at this time, the operation column will become "update" and "cancel". This is, we only need to modify the data we need to modify, then click Update Save Programs. (Update Events must write code).
The main steps are as follows:
First, start the attribute generator (do not know how to start, look at the article in front), then select the "column" on the left, in the "available column" on the right, we expand "button column", then, choose "Edit, Update, Cancel", click the ">" button to add it to "Selected Columns" so that our DataGrid will automatically add a column.
Then, return to the attribute window, add three events, one is the event editCommand generated after clicking the "Edit" link, one is an event of updating the data, UpdateCommand, one is a cancel event, canCaleCommand.
Add code in EditCommand, tell the program, the selected line needs to be edited: private void DataGrid1_editCommand (Object Source, System.Web.ui.WebControls.DataGridCommandeventArgs E)
{
DataGrid1.editItemIndex = (int) E.Item.itemindex; // tells DataGrid Sequence to edit
Bindgrid (); // I wrote in the first section, here is not repeated
}
After completing this code, you will find that it will focus on your choice to edit it according to your instruction. However, when you click "Update", "Cancel" link, it ignores you. This is because we have not written code for these two events, let's write "cancel" code:
Private void DataGrid1_cancelcommand (Object Source, System.Web.ui.WebControls.DataGridCommandeventArgs E)
{
DataGrid1.editItemIndex = -1; // Transfer -1 to the de-read statid of the DataGrid, it will return to read-only state
Bindgrid ();
}
Simple things, finished, we are doing the most responsible things - update data:
// Due to the case of the case, it has been re-made here.
Private void DataGrid1_UpdateCommand (Object Source, System.Web.ui.WebControls.DataGridCommandeventArgs E)
{
String updatecmd = "Update authors set au_id = @ID, au_lname = @lname, au_fname = @fname, phone = @Phone," "address = @address, city = @city, state = @State, Zip = @zip, Contract = @contract where au_id = @ID "; / / You should learn about parameterization programming in ADO.NET.
SqlCommand myCommand = new SqlCommand (updateCmd, myConnection); myCommand.Parameters.Add (new SqlParameter ( "@ Id", SqlDbType.NVarChar, 11)); myCommand.Parameters.Add (new SqlParameter ( "@ LName", SqlDbType.NVarChar , 40)); MyCommand.Parameters.add (New Sqlparameter ("@ fname", sqldbtype.nvarchar, 20)); MyCommand.Parameters.Add (New Sqlparameter ("@ phone", sqldbtype.nchar, 12); mycommand .Parameters.add ("@ address", sqldbtype.nvarchar, 40)); mycommand.parameters.add (New SqlParameter ("@ City", Sqldbtype.nvarchar, 20)); MyCommand.Parameters.Add (New SQLParameter ("@ State", Sqldbtype.Nchar, 2)); MyCommand.Parameters.Add (New SqlParameter ("@ zip", sqldbtype.nchar, 5)); mycommand.parameters.add (New Sqlparameter ("@ contract" , Sqldbtype.nvarchar, 1); mycommand.parameters ["@ ID"]. Value = mydatagrid.dataKeys [@Idatam.itemindex]; // This place forgot to tell you, we must set up in DataGrid DataKeyField property, mydatagrid.datakeys [(int) E.Item.itemindex] can get the desired keyword int number = E.Item.cells.count; for (int i = 2; i MyCommand.Parameters [cols [i-1]]. value = colvalue;} Mycommand.connection.open (); try {// Update data MyCommand.executenonQuery (); // Restore read-only status MyDataGrid.edititemindex = -1;} catch (SQLEXCEPTION EXC) {// error handling } myCommand.connection.close (); bindgrid (); // Re-bound data, use or write the same one } Ok, our work is done, this code looks very long, in fact, because it uses more fields, so I have to use more parameters, I use the key part with red characters. In fact, it is still very simple. Section 5: Delete entries It is simple to delete the entry for updated data relative to the fourth quarter. The key steps are as follows: Add a deleted button column, how to add to the fourth quarter. Set the DataGrid's DataKeyField property, you must be set to the keyword. Add a DeleteCommand event, write code: public void MyDataGrid_Delete (Object sender, DataGridCommandEventArgs e) {String deleteCmd = "DELETE from Employee where emp_id = @Id"; SqlCommand myCommand = new SqlCommand (deleteCmd, myConnection); myCommand.Parameters.Add (new SqlParameter ( "@ Id", Sqldbtype.nvarchar, 11)); mycommand.parameters ["@ id"]. Value = mydatagrid.datakeys [it); mycommand.Connection.Open (); try {mycommand.executenon query (); } catch (sqlexception) {} mycommand.connection.close (); bindgrid ();} 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 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"; } }