recently has been in the DataGridView, the previous article got a check box to delete, but later think, if I delete every row, then I delete every time you have to select, and then the area of a single delete, too troublesome, so I remembered to get a right button to delete, and then added a right button discoloration, Anyway is a right-click menu, the bottom bar code to everyone, very simple code, is really very practical.
<summary>////Add a table////</summary> public void adddatatable () {D Atacolumn dc = new DataColumn ("ID"); Dt. Columns.Add (DC); DC = new DataColumn ("name"); Dt. Columns.Add (DC); DC = new DataColumn ("Age"); Dt. Columns.Add (DC); DC = new DataColumn ("sex"); Dt. Columns.Add (DC); Assigns a DataTable value for (int i = 0; i < 6; i++) {DataRow row = dt. NewRow (); row["ID"] = i; row["name"] = "Menghaibin"; Row["age"] = i + 10; row["Sex" = "male"; Dt. Rows.Add (row); }}///<summary>///Get the coordinates of the currently selected unit///</summary>//<param name= "Sender" >< ;/param>//<param name= "E" ></param> private void Datagridview1_cellmouseenter (object sender , DataGridViewCellEventArgs e) { var DGV = (DataGridView) sender; CurrentRow = E.rowindex; Currentcolumn = E.columnindex; }///<summary>////////</summary>//<param name= "sender" in the right-click menu////></param& Gt <param name= "E" ></param> private void Modify Toolstripmenuitem_click (object sender, EventArgs e) {if (CurrentRow >-1 && currentcolumn >-1) {if (datagridview1.rows[c Urrentrow]. Cells[currentcolumn]. Selected) {DataGridViewCell AA = Datagridview1.rows[currentrow]. Cells[currentcolumn]; Aa. Style.forecolor = color.red; Aa. Style.backcolor = Color.pink; This.datagridview1.rows[currentrow]. Defaultcellstyle.forecolor = Color.Blue; This.datagridview1.columns[currentcolumn]. Defaultcellstyle.backcolor = Color.brown; Aa. Style.font = Font.undeRline; }} else {MessageBox.Show (this, "Please select the contents of the datasheet", "Prompt Information", MESSAGEBOXBUTTONS.OKC Ancel,messageboxicon.information); Return }}////<summary>///Click the Delete button in the context menu///</summary>//<param Name= "Sender" ></param>//<param name= "E" ></param> private void Delete TOOLSTRIPMENUITEM_CL Ick (object sender, EventArgs e) {//Gets the current row datagridviewrow row = Datagridview1.rows[currentrow ]; Delete line dataGridView1.Rows.Remove (row); Datagridview1.currentcell = Datagridview1[0, CurrentRow]; }<pre name= "code" class= "CSharp" > DataTable dt = new DataTable (); Define variables to store the selected number of rows private int CurrentRow {get; set;} private int Currentcolumn {get; set;} private void Form1_Load (object sender, EventArgs e) {adddatatable (); Datagridview1.datasource = DT; }
Not difficult, just a few lines of the whine, but let our code very human, said is the words, make this time, feel more than that a bunch of code to realize the joy of the function of the great.
DataGridView Right-click menu