23 Tips for C # development and use

Source: Internet
Author: User
Tags foreach command line expression message queue range tostring create database
1. How to customize Vc#datagrid column headings?

DataGridTableStyle Dgts = new DataGridTableStyle ();

Dgts. MappingName = "MyTable"; MyTable for 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. Retrieve a conditional statement for all records that have a blank field?

. where col_name is null

3. How to receive return enter input in C # WinForm application?

Set the AcceptButton of the form.

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

Number (15): Use numeric, Precision 15 try.

5.sql server How do I write a stored procedure that uses the like statement?

SELECT * FROM mytable where haoma like '% ' + @hao + '% '

How to let the TextBox accept the ENTER key message in the 6.vc# WinForm (without a button)?

private void Textbox1_keypress (object sender, System.Windows.Forms.KeyPressEventArgs e)

{

if (E.keychar!= (char) 13)

Return

Else

Do something;

}

7. Why (Int32) cmd. ExecuteScalar () when assigning to a Int32 variable, the prompt conversion is invalid?

Int32.Parse (cmd. ExecuteScalar (). ToString ());

8.DataSource How do I add a column to the DataGrid in the child table to display a field in the master table?

Manually add a column to the child table.

DataColumn dc = new DataColumn ("Newcol", Type.GetType ("System.String"));

dc. Expression = "Parent.parentcolumnname";

Dt. Columns.Add (DC); DT to child table

9. How do I make the DataGrid display only one part of the data in a DataTable?

Select ..., SUBSTR (String, Start_index, End_index) as * * *, * * * * FROM * * *

10. How to make the WinForm ComboBox can only choose not to input?

The DropDownStyle property determines whether the user can enter a new value in the text section and the list part is always displayed.

Value:

The DropDown---text section can be edited. The user must click the arrow button to display the list section.

DropDownList---Users cannot edit the text section directly. The user must click the arrow button to display the list section.

The simple---text section can be edited. The list section is always visible.

11. How to make the date displayed in the DataGrid of WinForm only show the month and day part, take out the time?

SQL statement plus to_date (date field, ' Yyyy-mm-dd ')

12. How to combine two columns of a database table into one column fill into a 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 do you extract the bracketed text from the merged field as a display for a DataGrid or other bound control? That is, the text between the left parenthesis (and the closing parenthesis) in the merged field contents is extracted.

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. The DataGrid loses focus when browsing the DataGrid data with the mouse wheel over a certain range. How to solve?

This.datagrid1.mousewheel+=new MouseEventHandler (Datagrid1_mousewheel);

private void Datagrid1_mousewheel (object sender, MouseEventArgs e)

{

This.dataGrid1.Select ();

}

15. How to make keyboard input ' + ' symbol into ' A '?

In the KeyPress event of the textbox

if (E.keychar = = ' + ')

{

Sendkeys.send ("A");

E.handled = true;

}

16. How to maximize the WinForm when starting?

This. WindowState = formwindowstate.maximized;

17.c# how to get the current date and time, what is in the SQL statement?

C #: DateTime.Now

SQL Server:getdate ()

18. How do I access a column of a row in the WinForm DataGrid, or each row of columns?

Datagrid[row,col]

19. How to summarize the DataTable, such as the column value of the DataTable ' Yanji '?

Dt. Select ("city = ' Yanji '"). Length;

20.DataGrid data exported to Excel 0212 will become 212. How do I make it export and continue to display 0212?

Range. NumberFormat = "0000";

21st.

How do ① export DataGrid data to Excel for printing?

② has previously set TableStyle for the DataGrid, that is, customizing the column headings and the columns to be displayed, what if you want to export the data in a custom view?

③ you export data to Excel, how do you set a border for it?

④ How do I align a column that is exported from the DataGrid to Excel?

When ⑤ data is exported from the DataGrid to Excel, how do I make the header row appear on each page when printed?

⑥datagrid data is exported to Excel, each page displays ' current page/page ', how to achieve it?

private void Button1_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=;d atabase=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;//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 = "&p page/Total &n page";

22. When assigning the cell contents of a DataGrid to Excel, you want to display progress on the captiontext of the DataGrid, but do not display it. WHY?

...

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

System.Windows.Forms.Application.DoEvents ();

...

  

Handles all Windows messages that are currently in the message queue.

When you run a Windows Form, it creates a new form, and the form waits for the event to be processed. The form handles all the code associated with the event each time the event is processed. All other events wait in the queue. The application does not respond when the code handles the event. If you call DoEvents in your code, the application can handle other events.

If you remove DoEvents from your code, the form is not redrawn until the button's stand-alone event handler finishes executing. This method is typically used in loops to process messages.

23. How to call external programs from flash, such as a C # compiled after the EXE?

Fscommand ("Exec", "Application. exe");

① must publish flash as an. exe

② must build a subdirectory named Fscommand in the directory of the. exe file generated by flash and copy the executable program to be called there.

24. Is there a way to control the DataGrid in the upper and lower, right and left scroll?

Datagrid1.select ();

Sendkeys.send ("{pgup}");

Sendkeys.send ("{PGDN}");

Sendkeys.send ("{^{left}");//Ctrl + LEFT ARROW

Sendkeys.send ("{^{right}");//Ctrl + RIGHT ARROW

25. How do I bind the two DataGrid to two master-subordinate relational tables?

DataGrid1.DataSource = ds;

DataGrid1.DataMember = "Master table";

...

Datagrid2.datasouce = ds;

Datagrid2.datamember = "Master table. Relationship name";

How can the version number of 26.assembly be generated automatically? In particular, the program is not written through the Vstudio environment under the console.

The key is [Assembly:assemblyversion ("1.0.*")] in AssemblyInfo.cs, which contains AssemblyInfo.cs when the command line is compiled

27. How to create a shared Assembly?

Use Sn.exe to generate a strong Name:keyfile.sn, placed in the source program directory

In the AssemblyInfo.cs of the project [Assembly:assemblykeyfile (". \\.. \\keyfile.sn ")]

After building the DLL, place the global Assembly Cach with gacutil/i MyDll.dll.

28. How do I get a record of the first letter of a field between uppercase and English a~z in Oracle?

SELECT * FROM table where ASCII (substr (field, 1,1)) between ASCII (' A ') and ASCII (' Z ')

29. How do I get the current assembly version number?

Process current = Process.getcurrentprocess ();

FileVersionInfo myfileversioninfo = Fileversioninfo.getversioninfo (current. Mainmodule.filename);

Console.WriteLine (myfileversioninfo.fileversion);

30. How to make a simple WinForm installation program?

① Build a WinForm application, the simplest kind. Run.

② Add new project-> install and deploy project, ' template ' Select ' Install Wizard '.

③ two consecutive ' next ', in ' select included project output ' step tick ' main output from ', two consecutive ' Next ', ' finish '.

④ generation.

⑤ to the project directory to find Setup.exe (there is also an. msi and. ini file), executed.

31. How do I build a table on a SQL Server database through the WinForm Setup program?

①[Project]-[Add New Item]

Categories: Code; Templates: Installer class.

Name: MyInstaller.cs

② builds a table in 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 Item]. mytable.sql-[build operations]-[embedded Resources].

④ switches MyInstaller.cs to Code view and adds the following code:

Add First:

Using System.Reflection;

Using System.IO;

And 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=;d atabase=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"); To build a database called MyDB.

}

⑤[Add New Project]-[Project type: Install and deploy Project]-[Template: Installation project]-[name: Mysetup].

⑥[Application Folder]-[add]-[project output]-[Primary output].

⑦ Solution Explorer-right--[Setup project (mysetup)]-[view]-[custom actions. [Install]-[Add custom action]-[Double-click: Application Folder] The main output is from * * * (Active).

32. How do I use the TreeView to display a parent-child Relationship database table (WinForm)?

Three table A1,A2,A3, A1 for A2 look at the master table, A2 for the A3 of the master table.

A1:id, Name

A2:id, parent_id, name

A3:id, parent_id, name

Use three DataAdapter to fill three tables into the dataset's three tables.

Set the relationship between three tables with DataRelation.

  

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 pass data from one form to another form?

Suppose the FORM2 data is passed to the Form1 textbox.

In Form2:

Define delegate

public delegate void SendData (object sender);

Create instance

Public SendData SendData;

In the Form2 button click event or other event code:

if (senddata!= null)

{

SendData (TXTBOXATFORM2);

}

This. Close (); Close Form2

In Form1 's 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.