如何使用VB.Net中的datagridview windowsform在我的复选框列中添加一个复选框

时间:2014-08-12 13:13:50

标签: sql vb.net checkbox datagridview

Private Sub Recipients_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    mycom.Connection = cn
    mycom.CommandText = <SQL> SELECT Idno,Name,YearSec,Course,Organization FROM tbl_students </SQL>.Value

    Dim myadap As New MySqlDataAdapter(mycom)
    Dim mydt As New DataTable

    mydt.Columns.Add("", GetType(Boolean))
    myadap.Fill(mydt)
    grdRecipients.DataSource = mydt

    myadap.Dispose()

End Sub

我在复选框列的标题中创建一个复选框时出现问题,该复选框应该是一个复选框,以便我可以检查数据网格视图中存在的所有行。 任何答案都会有很大帮助。感谢

1 个答案:

答案 0 :(得分:0)

尝试这样

    DataGridViewCheckBoxColumn c1;
    CheckBox ckBox;

   grdRecipients.DataSource = mydt

   ckBox = new CheckBox();

  //Get the column header cell bounds
  Rectangle rect =
  this.dataGridView1.GetCellDisplayRectangle(0, -1, true);
  ckBox.Size = new Size(18, 18);

  //Change the location of the CheckBox to make it stay on the header
  ckBox.Location = rect.Location;
  ckBox.CheckedChanged += new EventHandler(ckBox_CheckedChanged);

  //Add the CheckBox into the DataGridView
  this.dataGridView1.Controls.Add(ckBox);

以下方法用于选中取消选中所有复选框

     void ckBox_CheckedChanged(object sender, EventArgs e)
    {
        for (int j = 0; j < this.dataGridView1.RowCount; j++)
        {
            this.dataGridView1[0, j].Value = this.ckBox.Checked;
        }
        this.dataGridView1.EndEdit();
    }