C #32 skills in development and use

Source: Internet
Author: User

1. How to customize the VC # DataGrid column title?

 

Datagridtablestyle DGTS = new datagridtablestyle ();

DGTS. mappingname = "mytable"; // mytable is the datatable to load data.

Datagridtextboxcolumn DGCS = new datagridtextboxcolumn ();

DGCS. mappingname = "title_id ";

DGCS. headertext = "title ID ";

DGTS. gridcolumnstyles. Add (DGCS );

...

Datagrid1.tablestyles. Add (DGTS );

2. How do I write the condition statements for retrieving all records whose fields are null?

... Where col_name is null

3. How do I receive the Enter key in the C # winform application?

Set the form's acceptbutton.

4. For example, in Oracle number (15), what should I do in SQL Server?

Number (15): use numeric and try it with a precision of 15.

5. How to Write the like statement Stored Procedure for SQL Server applications?

Select * From mytable where haoma like '%' + @ hao + '%'

6. VC # In winform, how does one make textbox receive the carriage return key message (without buttons )?

Private void textbox1_keypress (Object sender, system. Windows. Forms. keypresseventargs E)

{

If (E. keychar! = (Char) 13)

Return;

Else

// Do something;

}

7. Why does the prompt that the conversion is invalid when (int32) cmd. executescalar () is assigned to the int32 variable?

Int32.parse (CMD. executescalar (). tostring ());

8. How to add a column to the DataGrid of the child table as datasource to display a field in the parent table?
Manually add a column to the table.

Datacolumn Dc = new datacolumn ("newcol", type. GetType ("system. String "));

DC. Expression = "parent. parentcolumnname ";

DT. Columns. Add (DC); // DT is a sub-table.

9. How to Make the DataGrid show only a certain part of the data of a column in the datatable?

Select..., substr (string, start_index, end_index) as ***, *** from ***

10. How can I make the ComboBox of winform only available?

The dropdownstyle attribute determines whether the user can enter a new value in the text section and whether the list section is always displayed.

Value:

Dropdown --- the text part can be edited. You must click the arrow to display the list.

Dropdownlist --- you cannot directly edit the text section. You must click the arrow to display the list.

Simple --- the text part can be edited. The list is visible.

11. How can I make the date displayed in the winform DataGrid show only the year, month, and day sections, and remove the time?

Add to_date to the SQL statement (Date Field, 'yyyy-mm-dd ')

12. How to merge the two columns of the database table into one column fill into dataset?

Dcchehao = new datacolumn ("newcolumnname", typeof (string ));

Dcchehao. Expression = "columnname1 + columnname2 ";

DT. Columns. Add (dcchehao );

ORACLE:

Select col1 | col2 from table

SQL Server:

Select col1 + col2 from table

13. how to extract the text in parentheses from the merged fields as the display content of the DataGrid or other bound controls? Extract the text between the left and right brackets in the merged field content.

Select col1, col2, Case

When col3 like '% (%' Then substr (col3, instr (col3, '(') + 1, instr (col3, ')-instr (col3, '(')-1)

End as col3

From my_table

14. When you use the scroll wheel to browse the DataGrid data beyond a certain range, the DataGrid will lose the focus. How can this problem be solved?

This. Maid + = new mouseeventhandler (maid mousewheel );

Private void maid (Object sender, mouseeventargs E)

{

This. Maid ();

}

15. How can I change the '+' symbol entered by the keyboard to 'A '?
In the keypress event of textbox

If (E. keychar = '+ ')

{

Sendkeys. Send ("");

E. Handled = true;

}

16. How can I maximize the value of winform when it is started?

This. windowstate = formwindowstate. maximized;

 
17. C # How to get the current date and time? What is it in SQL statements?

C #: datetime. Now

SQL Server: getdate ()

18. How to access a certain column in a row of the winform DataGrid or each column in each row?

DataGrid [row, Col]

19. How to make a summary for the datatable? For example, how many columns of the 'yanji 'column value of the datatable?

DT. Select ("city = 'yanji"). length;

20. After the DataGrid data is exported to excel, 0212 and so on will change to 212. How can I export it and continue to display it as 0212?

Range. numberformat = "0000 ";

21.

① How to export data from the DataGrid to excel for printing?

② Previously, tablestyle has been set for the DataGrid, that is, the column title and the column to be displayed have been customized. What should I do if I want to export data in a custom view?

③ After exporting data to excel, how can I set a border for it?

④ How to align a column exported from DataGrid to excel in the center?

⑤ After the data is exported from the DataGrid to excel, how does one display the title row on each page during printing?

6. How can I achieve this when the data in the DataGrid is exported to excel and the current page/total pages are displayed on each page?

Private void button#click (Object sender, system. eventargs E)
{
Int row_index, col_index;
Row_index = 1;
Col_index = 1;
Excel. applicationclass Excel = new excel. applicationclass ();
Excel. workbooks. Add (true );
Datatable dt = Ds. Tables ["table"];
Foreach (datacolumn dcheader in DT. columns)
Excel. cells [row_index, col_index ++] = dcheader. columnname;
Foreach (datarow DR in DT. Rows)
{
Col_index = 0;
Foreach (datacolumn DC in DT. columns)
{
Excel. cells [row_index + 1, col_index + 1] = Dr [DC];
Col_index ++;
}
Row_index ++;
}
Excel. Visible = true;
}

Private void form1_load (Object sender, system. eventargs E)
{
Sqlconnection conn = new sqlconnection ("Server = Tao; uid = sa; Pwd =; database = pubs ");
Conn. open ();

Sqldataadapter da = new sqldataadapter ("select * from authors", Conn );
DS = new dataset ();
Da. Fill (DS, "table ");
Datagrid1.datasource = Ds;
Datagrid1.datamember = "table ";
}

 

② Datagrid1.tablestyles [0]. gridcolumnstyles [Index]. headertext; // The index can be from 0 ~ Datagrid1.tablestyles [0]. gridcolumnstyles. Count traversal.

③ Excel. Range range;

Range = worksheet. get_range (worksheet. cells [1, 1], XST. cells [Ds. tables [0]. rows. count + 1, DS. tables [0]. columns. count]);

Range. borderaround (Excel. xllinestyle. xlcontinuous, Excel. xlborderweight. xlthin, Excel. xlcolorindex. xlcolorindexautomatic, null );

Range. Borders [Excel. xlbordersindex. xlinsidehorizontal]. colorindex = excel. xlcolorindex. xlcolorindexautomatic;

Range. Borders [Excel. xlbordersindex. xlinsidehorizontal]. linestyle = excel. xllinestyle. xlcontinuous;

Range. Borders [Excel. xlbordersindex. xlinsidehorizontal]. Weight = excel. xlborderweight. xlthin;

Range. Borders [Excel. xlbordersindex. xlinsidevertical]. colorindex = excel. xlcolorindex. xlcolorindexautomatic;

Range. Borders [Excel. xlbordersindex. xlinsidevertical]. linestyle = excel. xllinestyle. xlcontinuous;

Range. Borders [Excel. xlbordersindex. xlinsidevertical]. Weight = excel. xlborderweight. xlthin;

④ Range. horizontalalignment = excel. xlhalign. xlhaligncenter

⑤ Worksheet. pagesetup. printtitlerows = "$1: $1 ";

⑥ Worksheet. pagesetup. centerfooter = "Page & P/total & N ";

22. When you assign the cell content of the DataGrid to excel, you want to display the progress on the DataGrid captiontext, but not the progress. Why?

...

Datagrid1.captiontext = "exporting:" + (row + 1) + "/" + row_cnt;

System. Windows. Forms. application. doevents ();

...


Processes All Windows messages in the message queue.

When running a Windows form, it creates a new form and waits for processing the event. This form processes allCode. All other events are waiting in the queue. When the code processes events, the applicationProgramDoes not respond. If doevents is called in the Code, the application can process other events.

If doevents is removed from the Code, the form will not be re-drawn until the button's standalone event handler is executed. This method is usually used in a loop to process messages.

23.how can I use an external program, such as A. EXE compiled by a CEN?

Fscommand ("EXEC", "application .exe ");

① The flashpath is .exe.

② Construct a subdirectory named fscommand in the directory where the generated .exe file is located, and copy the executable program to be called to it.

24. Is there a way to use code to control the scroll between the top, bottom, and left of the DataGrid?

Datagrid1.select ();

Sendkeys. Send ("{pgup }");

Sendkeys. Send ("{pgdn }");

Sendkeys. Send ("{^ {left}"); // Ctrl + left arrow key

Sendkeys. Send ("{^ {right}"); // Ctrl + right arrow key

25. How can I bind two DataGrid tables with two master-slave relationships?

Datagrid1.datasource = Ds;

Datagrid1.datamember = "parent table ";

...

Datagrid2.datasouce = Ds;

Datagrid2.datamember = "parent table. Link name ";

 

26. How can I automatically generate the assembly version number? Especially when the program is not written in the vstudio environment on the console.

The key is [Assembly: assemblyversion ("1. 0. *")] In assemblyinfo. cs. The command line compilation contains assemblyinfo. CS.

27. How to create a shared assembly?

Use sn.exe to generate a strong name: Keyfile. Sn, which is stored in the source program directory.

In assemblyinfo. CS of the project [Assembly: assemblykeyfile (".. \ Keyfile. Sn")]

After the DLL is generated, put gacutil/I mydll. DLL into global assembly cach.

28. How to obtain the first letter of a field in Oracle in uppercase ~ Between Z records?

Select * from table where ASCII (substr (field, 1, 1) between ASCII ('A') and ASCII ('Z ')

29. How to obtain the current Assembly version number?

Process current = process. getcurrentprocess ();

Fileversioninfo myfileversioninfo = fileversioninfo. getversioninfo (current. mainmodule. filename );

Console. writeline (myfileversioninfo. fileversion );

 
30. How to create a simple winform installer?

① Create a winform application, the simplest one. Run.

② Add a new project-> install and deploy the project. Select 'installation wizard 'as the 'template '.

③ There are two consecutive 'Next'. In the 'select included project output' step, tick 'Primary output from', two consecutive 'Next' and 'complete '.

④ Generate.

⑤ Go to the project directory and find setup.exe (there is also a. MSI and. ini file.

31. How to Create a table on the SQL Server database through the winform installer?

① [Project]-[add new project]

Type: Code; Template: installer class.

Name: myinstaller. CS

② Create a table on SQL Server and then [all tasks]-[generate SQL Scripts].

Generate a script similar to the following (Note: Remove all go statements ):

If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [mytable] ') and objectproperty (ID, n'isusertable') = 1)
Drop table [DBO]. [mytable]
Create Table [DBO]. [mytable] (
[ID] [int] not null,
[Name] [nchar] (4) Collate chinese_prc_ci_as not null
) On [primary]

Alter table [DBO]. [mytable] With nocheck add
Constraint [pk_mytable] primary key clustered
(
[ID]
) On [primary]

 
③ [Project]-[add existing items]. Mytable. SQL-[generate operations]-[embedded resources].

④ Switch myinstaller. CS to the Code view and add the following code:

Add:

Using system. reflection;
Using system. IO;
Then:

Private string getsql (string name)
{
Try
{
Assembly ASM = assembly. getexecutingassembly ();
Stream STRM = ASM. getmanifestresourcestream (ASM. getname (). Name + "." + name );
Streamreader reader = new streamreader (STRM );
Return reader. readtoend ();
}

Catch (exception ex)
{
Console. Write ("in getsql:" + ex. Message );
Throw ex;
}
}

Private void executesql (string databasename, string SQL)
{
System. Data. sqlclient. sqlconnection sqlconn = new system. Data. sqlclient. sqlconnection ();
Sqlconn. connectionstring = "Server = myserver; uid = sa; Password =; database = Master ";
System. Data. sqlclient. sqlcommand command = new system. Data. sqlclient. sqlcommand (SQL, sqlconn );

Command. Connection. open ();
Command. Connection. changedatabase (databasename );

Try
{
Command. executenonquery ();
}

Finally
{
Command. Connection. Close ();
}
}

Protected void adddbtable (string strdbname)
{
Try
{
Executesql ("master", "create database" + strdbname );
Executesql (strdbname, getsql ("mytable. SQL "));
}

Catch (exception ex)
{
Console. Write ("in exception handler:" + ex. Message );
}
}

Public override void install (system. Collections. idictionary statesaver)
{
Base. Install (statesaver );
Adddbtable ("mydb"); // create a database named mydb
}

 

⑤ [Add a new project]-[project type: installation and deployment project]-[template: Installation Project]-[name: mysetup].

6. [Application folder]-[add]-[project output]-[main output].

7. Solution Explorer-right-click [installation project]-[view]-[custom operations]. [Install]-[add custom operation]-[double-click: Application folder] [main output from *** (activity)].

32. How to Use Treeview to display the winform of the parent-child relationship )?

The three tables A1, A2, A3, and A1 are the parent tables for A2 and A2 is the A3.

A1: ID, name

A2: ID, parent_id, name

A3: ID, parent_id, name

Use three dataadapters to add the three tables to the three dataset tables.

Use datarelation to set the relationship between the three tables.

 

Foreach (datarow dra1 in DS. Tables ["A1"]. Rows)
{
TN1 = new treenode (dra1 ["name"]. tostring ());
Treeview1.nodes. Add (TN1 );
Foreach (datarow dra2 in dra1.getchildrows ("a1a2 "))
{
TN2 = new treenode (dra2 ["name"]. tostring ());
Tn1.nodes. Add (TN2 );

Foreach (datarow dra3 in dra2.getchildrows ("a2a3 "))
{
Tn3 = new treenode (dra3 ["name"]. tostring ());
Tn2.nodes. Add (tn3 );
}
}
}

33. How to transmit data from one form to another?

Assume that the form2 data is transmitted to the textbox of form1.

In form2:

// Define delegate
Public Delegate void senddata (Object sender );
// Create instance
Public senddata;

 

Click the event or other event code in the form2 button:

If (senddata! = NULL)
{
Senddata (txtboxatform2 );
}
This. Close (); // close form2

In the form1 pop-up form2 code:
Form2 form2 = new form2 ();
Form2.senddata = new form2.senddata (myfunction );
Form2.showdialog ();

================================

Private void myfunction (Object sender)
{
Textbox1.text = (textbox) sender). text;
}

 

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.