Tips on the datagridview

Source: Internet
Author: User

Datagridview is a powerful and flexible data display and editing control. A large number of simple and practical development skills related to the datagridview are circulating on the Internet. however, it is not easy to find out what you really need from the messy network resources. therefore, we will sort out several commonly used dview techniques for your reference.

Use the image to describe the related skills involved in this article:

I. Calculation of data column count and summary

Let's take a look.CodeLet's talk about it again:

/// <Summary>
/// Calculate the quantity and total amount of various States
/// </Summary>
/// <Returns> </returns>
Private void setitemcount ()
{
Int refilling = 0, success = 0, failed = 0, totalcount = 0;
Decimal totalrefillmoney = 0, totalcharge = 0;
For (INT I = 0; I <datagridview1.rows. Count; I ++)
{
Int state = convert. toint16 (maid ["statecodedatagridviewtextboxcolumn", I]. value );
Decimal refillmoney = convert. todecimal (datagridview1 ["refillmoneydatagridviewtextboxcolumn", I]. value );
Decimal charge = convert. todecimal (datagridview1 ["chargedatagridviewtextboxcolumn", I]. value );
Switch (state)
{
Case 3:
Failed ++;
Break;
Case 2:
Success ++;
Break;
Case 0:
Case 1:
Default:
Refilling ++;
Break;
}
Totalcount ++;
Totalrefillmoney + = refillmoney;
Totalcharge + = charge;
}

If (totalcount = maid. Count)
{
Lbrefilling. Text = string. Format ("{0}", refilling );
Lbsuccess. Text = string. Format ("{0}", success );
Lbfailed. Text = string. Format ("{0}", failed );
Lbtotal. Text = string. Format ("Total: Charge/refillmoney = {1}/{0}", totalrefillmoney, totalcharge );
}
}

This code is a private method. It calculates the number of States (successful, failed, and ongoing) based on the value of the statecode column and calculates the sum of the amount columns. then it is displayed in the tag control. we only need to call this method after refreshing or retrieving data. of course, some may think it would be better to calculate in the event rowprepaint or cellprepaint of the dview itself. this is of course a good choice, but these events will be executed during the first re-painting. in fact, most of the time the re-painting is not because the data has changed. At this time, it was originally not necessary to re-calculate the number and sum of data, which greatly increased the calculation workload of the system, when the data volume is large, its drawbacks become more obvious. put the calculation in the method and can be called only when needed. For example, you can re-retrieve the data, modify the data, or add or delete rows.

2. Add image columns and replace cell content

The use of images will make the original seemingly boring pure data listing more vivid. therefore, many users want to add appropriate images to their datagridview to achieve better display.
We can add an image column in the "Edit column" named "image", and then display different images based on different cell data in the cellformatting event. The sample code is as follows:

Private void maid (Object sender, maid E)
{
If (maid [E. columnindex]. Name) = "image ")
{
Switch (convert. toint16 (datagridview1 ["statecodedatagridviewtextboxcolumn", E. rowindex]. Value )))
{
Case 2:
E. value = imagelist1.images ["trayxp_green.ico"];
Break;
Case 3:
E. value = imagelist1.images ["trayxp_red.ico"];
Break;
Case 0:
Case 1:
Default:
E. value = imagelist1.images ["trayxp_purple.ico"];
Break;
}
}
}

Careful friends may find that in this code segment, we used an imagelist control named imagelist1, and added several ICO images to it in advance. it is worth mentioning that the cellformatting event is used here, which is a very important datagridview event. Many pre-displayed content can be completed here, such as cell content replacement and background color modification. just change the text above:

If (maid [E. columnindex]. Name) = "statecodedatagridviewtextboxcolumn ")
{
Switch (convert. toint16 (E. Value ))
{
Case 2:
E. cellstyle. backcolor = color. lightgreen;
E. value = "success ";
Break;
Case 3:
E. cellstyle. backcolor = color. lightpink;
E. value = "failed ";
Break;
Case 0:
Case 1:
Default:
E. value = "Refilling ";
Break;
}
}

Iii. flexible query of datagridview data

When the data source of the datagridview control is bound to the dataadapter, we usually use the commandtext string statement in the selectcommand object of dataadapter as the SELECT statement for reading data from the database. when we add a new query method through the "add query" function of the datagridview control on the designer interface, we actually add a selectcommand object to the dataadapter bound to it, by setting the commandtext statement of the new object, you can use the new parameter to complete the new query function. this method is easy to use, but not flexible and powerful. the most flexible and powerful method is to generate the where condition section of the SELECT statement by yourself, and then replace the commandtext section of the existing selectcommand object with the new SQL statement. example:

Private void toolbarquery_click (Object sender, eventargs E)
{
String querystring = tx_querystring.text.trim (); // This is the custom where part.
If (querystring. length> 0)
{
String oldsql = string. empty;
String newsql = string. empty;
Try
{
Oldsql = This. accounttableadapter. Adapter. selectcommand. commandtext;
String clearsql = oldsql. Replace ("Top 100", ""). Replace ("order by id desc ","");
Newsql = clearsql + "" + querystring + "order by id desc ";
This. accounttableadapter. Adapter. selectcommand. commandtext = newsql;
This. accounttableadapter. Fill (this. refillingdataset. Account );
}
Catch (exception)
{
MessageBox. Show ("SELECT command error: \ r \ n" + newsql, text );
}
Finally
{
This. accounttableadapter. Adapter. selectcommand. commandtext = oldsql;
}
}
Else
{
This. accounttableadapter. Fill (this. refillingdataset. Account );
}
}

Note: you must first save the original SQL statement and use the new SELECT statement before replacing it. otherwise, I don't know what it will look like after several replicas. in addition, when the new SQL statement is wrong, you should promptly remind the user and replace the original statement.

4. display the drop-down list box in the datagridview

The drop-down list box is introduced in two cases. One is to associate the drop-down list box with a table in dataset, that is, the drop-down list table data comes from the table. the other is the predefined values of the drop-down list.

The previous one is relatively simple. You only need a few mouse clicks to edit the column. When editing the column, the columntype of the column to be displayed in the drop-down list box is set to datagridviewcomboboxcolumn, then, specify or create a bindingsource for it in the datasource attribute of the column, and then specify the fields and data fields to be displayed for it. the display field (displaymember) is the column corresponding to the text we see on the interface, and the data field (valuemember) is the true value of the column, this value is consistent with the value in the database.

After you set the column as datagridviewcomboboxcolumn, you also need to write your own code to declare a datatable. define its columns, add data to the able, bind it to the column to be displayed as a drop-down box, and specify the datatable columns corresponding to displaymember and valuemember. for example:

Private system. Data. datatable dt = new system. Data. datatable ();
DT. Columns. Add ("level", system. type. GetType ("system. String "));
DT. Rows. Add ("1 ");
DT. Rows. Add ("2 ");
DT. Rows. Add ("3 ");
This. powerlevel. datasource = This. DT; // Where powerlevel is the column name in the dview
This. powerlevel. displaymember = "level ";
This. powerlevel. valuemember = "level ";

Here, DT adds only one column and sets both the display field and data field to this column.

5. Display password characters in the datagridview

There are multiple ways to display password characters in the datagridview, such as hiding the real password column and adding a "shadow" column to display several asterisks. these are not what we really want (we hope that we can easily enter and change the password as the password in the text box, but do not display the text content ). the following code describes how to design a real password box:

Private void thedatagridview_cellformatting (Object sender, datagridviewcellformattingeventargs E)
{
If (thetablename = "user ")
{
// Display the password:
If (thedatagridview. Columns [E. columnindex]. Name = "password" & E. value! = NULL & E. value. tostring (). length> 0)
{
E. value = new string ('*', E. value. tostring (). Length );
}
}
}

Private void thedatagridview_editingcontrolshowing (Object sender, datagridvieweditingcontrolshowingeventargs E)
{
If (thetablename = "user ")
{
// Edit the password:
Textbox T = E. Control as textbox;
If (T! = NULL)
{
For (INT I = 0; I <thedatagridview. Columns. Count; I ++)
{
If (this. thedatagridview. Columns [I]. Name = "password ")
T. passwordchar = '*';
Else
T. passwordchar = new char ();
}
}
}
}

In fact, it is very easy to replace the original password content with a star number in the cellformatting event (Hehe, the above technique is used again), and edit the password in the editingcontrolshowing event. the key here is "textbox T = E. control as textbox; ", which makes the current cell have the text box feature. in this way, editing is as simple as editing the password in the text box. in addition, it is very intuitive to update the data in cells without any additional processing.

6. Specify the default value for the new column.

A user-friendlyProgram, Usually for user operations to specify the appropriate default value, which can reduce user operations in a certain program, improve operation efficiency. this is particularly important in operations on the datagridview. some Columns cannot be empty. if you forget to input data, an error message is displayed. therefore, it is necessary to specify an appropriate default value for each column of the newly added row. then we need to use the defaultvaluesneeded event.

Private void thedatagridview_defavaluvaluesneeded (Object sender, datagridviewroweventargs E)
{
E. Row. cells ["username"]. value = "user ";
E. Row. cells ["password"]. value = "8888 ";
E. Row. cells ["powerlevel"]. value = "2 ";
E. Row. cells ["remark"]. value = "default password is '000000'. the user can change it by himself .";
}

These tips are not advanced and often used. I believe they are of some value for beginners. If you have any questions, please let me know.

<End>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.