DataGrid相关知识总结(收集自各位老大处)

关于datagrid的问题,如何使行宽不可由用户更改。(即行宽固定,不能通过拖拉的方式改变)
定义DataGrid的时候就把宽度设定
<asp:BoundColumn ...>                       <HeaderStyle Width="150px"></HeaderStyle>

如何在winform中DataGrid点击某行,使数据实时显示在TEXTBOX中?
datagrid的keypress事件中

textbox1.text=mydatagrid(mydatagrid.currentcell.rownumber,0)
textbox2.text=mydatagrid(mydatagrid.currentcell.rownumber,1)
........

以此类推

namespace DataGridDoubleClick
{
 using System;
 using System.Drawing;
 using System.Collections;
 using System.ComponentModel;
 using System.Windows.Forms;
 using System.Data;

 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.DataGrid dataGrid1;
  private DataSet myDataSet;
  DateTime gridMouseDownTime;
    private System.Windows.Forms.Label label1;
  
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   InitializeComponent();
   gridMouseDownTime = DateTime.Now;
   SetUp();
  }

  private void SetUp()
  {
   // 用2个Table和1和Relation创建DataSet
   MakeDataSet();
   // 数据绑定
   dataGrid1.SetDataBinding(myDataSet, "Customers");

   //添加样式
   AddCustomDataTableStyle();
  }

  private void MakeDataSet()
  {
   // 创建DataSet.
   myDataSet = new DataSet("myDataSet");
      
   // 创建2个DataTables.
   DataTable tCust = new DataTable("Customers");
   
   // 创建两个列,并添加到第一个表
   DataColumn cCustID = new DataColumn("custID");
   DataColumn cCustName = new DataColumn("custName");
   DataColumn cCurrent = new DataColumn("custCity");
   tCust.Columns.Add(cCustID);
   tCust.Columns.Add(cCustName);
   tCust.Columns.Add(cCurrent);

   // 把tables添加到DataSet.
   myDataSet.Tables.Add(tCust);
   
   
   /* 计算tables.对每个客户,创建DataRow变量 */
   DataRow newRow1;
   
   // 添加记录到 Customers Table.
   for(int i = 1; i < 4; i++)
   {
    newRow1 = tCust.NewRow();
    newRow1["custID"] = (100*i).ToString();
    tCust.Rows.Add(newRow1);
   }

   tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";
   tCust.Rows[1]["custName"] = "net_lover";
   tCust.Rows[2]["custName"] = "http://xml.sz.luohuedu.net/";


   tCust.Rows[0]["custCity"] = "北京";
   tCust.Rows[1]["custCity"] = "上海";
   tCust.Rows[2]["custCity"] = "河南";
  }

  private void AddCustomDataTableStyle()
  {
   DataGridTableStyle ts1 = new DataGridTableStyle();
   ts1.MappingName = "Customers";
   // 设置属性
   ts1.AlternatingBackColor = Color.LightGray;

   // 添加Textbox列样式,以便我们捕捉鼠标事件
   DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custID";
   TextCol.HeaderText = "序号";
   TextCol.Width = 100;

   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custName";
   TextCol.HeaderText = "姓名";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custCity";
   TextCol.HeaderText = "地址";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);
  
    dataGrid1.TableStyles.Add(ts1);
   
  }

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  private void InitializeComponent()
  {
      this.dataGrid1 = new System.Windows.Forms.DataGrid();
      this.label1 = new System.Windows.Forms.Label();
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
      this.SuspendLayout();
      //
      // dataGrid1
      //
      this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;
      this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;
      this.dataGrid1.CaptionVisible = false;
      this.dataGrid1.DataMember = "";
      this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
      this.dataGrid1.Location = new System.Drawing.Point(11, 9);
      this.dataGrid1.Name = "dataGrid1";
      this.dataGrid1.Size = new System.Drawing.Size(368, 144);
      this.dataGrid1.TabIndex = 0;
      this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);
      //
      // label1
      //
      this.label1.Location = new System.Drawing.Point(4, 166);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(383, 23);
      this.label1.TabIndex = 1;
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      this.label1.Click += new System.EventHandler(this.Form1_Click);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(387, 201);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.label1,
                                                                  this.dataGrid1});
      this.Name = "Form1";
      this.Text = "鼠标双击事件的例子";
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
      this.ResumeLayout(false);

    }
  #endregion

  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void TextBoxDoubleClickHandler(object sender, EventArgs e)
  {
   MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
  }

  private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)
  {
   if(DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))
   {
     MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
   }
   label1.Text = "TextBox 鼠标按下了。  ";
  }

  private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
   gridMouseDownTime = DateTime.Now;
   label1.Text = "DataGrid1 鼠标按下了。  ";
  }

    private void Form1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
    private void label1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
 }

this.myDataGrid.CurrentCellChanged += new
System.EventHandler(this.myDataGrid_CurrentCellChanged);

///

private void myDataGrid_CurrentCellChanged(object sender,
System.EventArgs e)
{
   textBox1.Text = "Col is " + myDataGrid.CurrentCell.ColumnNumber
      + ", Row is " + myDataGrid.CurrentCell.RowNumber
      + ", Value is " + myDataGrid[myDataGrid.CurrentCell];
}


把 dsCustomers1和Customers换成你的
private void dataGrid1_Click(object sender, System.EventArgs e)
{
textBox1.BindingContex[this.dsCustomers1,"Customers"].Position=dataGrid1.BindingContext[this.dsCustomers1.Customers].Position;
}


datagrid的curserchange事件中

textbox1.text=mydatagrid(mydatagrid.currentcell.rownumber,0)
textbox2.text=mydatagrid(mydatagrid.currentcell.rownumber,1)
........

以此类推


textbox控件绑定dataset就行了
textBox1.DataBindings.Add(new Binding("Text", ds, "customers.custName"));


在DataGrid的TableSytle属性中设datagridTableStyle(MappingName为表名),再在其中按你要的次序加入自定义的DataGridTextBoxColumn(MappingName为字段名).每个DataGridTextBoxColumn可以独立设定宽度,。

在winforms datagrid中

1。如何实现行交替变色

2。如何加入链接(例如在 datagrid里放了订单表 ,想点击行中的任何列 可以弹出一个新的form ,放这个订单的---- 用户信息)

3。如何批量删除datagrid里的信息(用了checkBox


DataGridTableStyle ts1 = new DataGridTableStyle();
dataGrid1.DataSource = aTable;

// Specify the table from dataset (required step)
ts1.MappingName = "A";
   
// Set other properties (optional step)
ts1.AlternatingBackColor = Color.LightBlue;
//ts1.AllowSorting = false;
ts1.BackColor = Color.Cyan;
dataGrid1.TableStyles.Add(ts1);
ts1.GridColumnStyles[0].Width = 200;
ts1.DataGrid.Refresh();

你的第一個問題我給一個例子給你:

datagrid 的樣式表(DataGridTableStyle)應用...
首先 我們先定一個 datatable 和 一個datarow

  Private idtb_temp As New DataTable
  Private idrw_row As DataRow

  private sub GetDataTable()
         idtb_temp.Columns.Add("prdodr_subodr_code")              '''定義datatable 的列名

        idtb_temp.TableName = "SearchTable"
        Dim ldcl_header As Windows.Forms.DataGridTextBoxColumn
        Dim ldgts_styles As New Windows.Forms.DataGridTableStyle
        ldgts_styles.SelectionForeColor = System.Drawing.Color.Yellow  
         '''選中行的前景色,即字體顏色
        ldgts_styles.SelectionBackColor = System.Drawing.Color.Brown     '''選中行的背景色

        ldgts_styles.ForeColor = System.Drawing.Color.Coral          
        ''' datagrid 中將要顯示的字的顏色
        ldgts_styles.AlternatingBackColor = System.Drawing.Color.Cyan  
         '''datagrid中奇數行所顯示的顏色
        ldgts_styles.BackColor = System.Drawing.Color.Cyan           
       '''datagrid中偶數行所顯示的顏色

        ldgts_styles.AllowSorting = False                             
         '''些樣式表定義datagrid不允許自動排序..

        ldgts_styles.MappingName = "SearchTable"

        ldcl_header = New Windows.Forms.DataGridTextBoxColumn         
         '''實例化一個datagridtextboxcolumn
        ldcl_header.MappingName = "prdodr_subodr_code"        
        '''引用前面定義的 “列名”
        ldcl_header.HeaderText = "第一列"                                               
       '''datagrid 中顯示的 表列頭 文字
        ldcl_header.ReadOnly = True            '''些列設定為只讀
        ldcl_header.TextBox.BorderStyle = BorderStyle.Fixed3D
        ldcl_header.TextBox.ForeColor = System.Drawing.Color.Red

        ldgts_styles.GridColumnStyles.Add(ldcl_header)

        For i As Integer = 0 To 7
            idrw_row = idtb_temp.NewRow
            idrw_row.Item("prdodr_subodr_code") = "第" & i & "行"
            idtb_temp.Rows.Add(idrw_row)

        Next

        idtb_temp.DefaultView.AllowNew = False
        Me.DataGrid1.TableStyles.Add(ldgts_styles)
        Me.DataGrid1.DataSource = idtb_temp
  end sub


第三問題:看我的blog
在datagrid 中使用Checkbox, ComboBxo 和 datetimepicker

http://blog.csdn.net/zwxrain/archive/2005/01/19/258998.aspx


1.在为DataGrid设置了数据源DataSource后,可添加DataGridTableStyle,然后设置其AlternatingBackColor属性和BackColor属性就是交替行的颜色了

主  题:  DataGrid 中间单元格点击触发事件是什么? 

private void dataGrid1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
 
{
 
     System.Drawing.Point pt = new Point(e.X, e.Y);
 
     DataGrid.HitTestInfo hti = dataGrid1.HitTest(pt);
 
     if(hti.Type == DataGrid.HitTestType.Cell)
 
     {
 
          dataGrid1.CurrentCell = new DataGridCell(hti.Row, hti.Column);
 
          dataGrid1.Select(hti.Row);
 
     }
 
}

1.分页;用属性生成器分页后,上页 下页 和页码的click代码该怎么写?

2.编辑;编辑功能该如何的实现。

自己看msdn,看的没头绪,向各位高手请教点思路。多谢!!

分页:
public void dg_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
BindData();
}
编辑:
public void edit(object sender,DataGridCommandEventArgs e)
{
type_dg.EditItemIndex=e.Item.ItemIndex;
BindData();
}
public void update(object sender,DataGridCommandEventArgs e)

TextBox id=(TextBox)e.Item.Cells[0].Controls[0];
TextBox name=(TextBox)e.Item.Cells[1].Controls[0];
TextBox num=(TextBox)e.Item.Cells[2].Controls[0];
string update_OleDb="update blog_type set b_type_name='"+name.Text+"',b_type_num='"+num.Text+"' where id='"+id.Text+"'";
OleDbConnection myconn=new OleDbConnection(Application["strconn"].ToString());
myconn.Open();
OleDbCommand update_com=new OleDbCommand(update_OleDb,myconn);
update_com.ExecuteNonQuery();

type_dg.EditItemIndex=-1;
myconn.Close();
BindData();
}

public void cancel(object sender,DataGridCommandEventArgs e)
{
type_dg.EditItemIndex=-1;
BindData();
}


删除:
public void delete(object sender,DataGridCommandEventArgs e)
{
string no=type_dg.Items[e.Item.ItemIndex].Cells[0].Text;
OleDbConnection myconn=new OleDbConnection(Application["strconn"].ToString());
myconn.Open();
string deleteOleDb="delete from blog_type where id="+no;
OleDbCommand deletecom=new OleDbCommand(deleteOleDb,myconn);
deletecom.ExecuteNonQuery();
myconn.Close();
BindData();
}

在winform的dataGrid中如何更改列的标题和设置列内容。


表:
id  name strdate   enddate     
1   a     2004/2/1  2005/2/1 

要求显示出来
名称     开始日期        结束日期     逾期(是/否)
a        2004/2/1       2005/2/1      逾期365天
谢谢!


private void Form1_Load(object sender, System.EventArgs e)
{
  SqlConnection CS = new SqlConnection("server=mengxianhui;database=SqlPUB2;User Id=sa;password=");
  SqlDataAdapter myCommand = new SqlDataAdapter("Select lastmodified,objectId from BaseObject", CS);
  DataSet myDataSet = new DataSet();
  myCommand.Fill(myDataSet, "BaseObject");
  this.dataGrid1.DataSource = myDataSet.Tables[0];
  //设置DataGrid的各列
  DataGridTextBoxColumn c1=new DataGridTextBoxColumn();
  DataGridTextBoxColumn c2=new DataGridTextBoxColumn();

  c1.MappingName = "lastmodified";
  c2.MappingName = "objectId";

  c1.HeaderText="时间【你好,夏威夷】";
  c2.HeaderText="标号";
  c1.Format="yyyy年MM月dd日";
  c1.Width = 200;

  DataGridTableStyle dts=new DataGridTableStyle();
  dts.GridColumnStyles.Add(c1);
  dts.GridColumnStyles.Add(c2);
  dts.MappingName="BaseObject";
  this.dataGrid1.TableStyles.Add(dts);
}

主  题:  DataGrid+CheckBoxList应用问题 

你可以添加一个模板列,然后对模板列进行编辑,加入一个CheckBox和一个CheckBoxList,然后命名这两个控件,在CODE加入CheckBox1_CheckedChanged事件,把CheckBox的Auto PostBack设置为true,再在
CheckBox1_CheckedChanged事件写你所要实现的功能。


下面是一个简单例子,删除DataGrid当前行数据:(前面数据已经绑定到dataGrid1了)

string strSQL = "DELETE FROM Table1 WHERE Id=@Id";
string text = dataGrid1[dataGrid1.CurrentCell.RowNumber, 0].ToString();
testDataSet1.Table1.Rows[dataGrid1.CurrentCell.RowNumber].Delete();
testDataSet1.AcceptChanges();
sqlDataAdapter2.DeleteCommand.Parameters["@Id"].Value = text;
sqlDataAdapter2.DeleteCommand.Connection.Open();
sqlDataAdapter2.DeleteCommand.ExecuteNonQuery();
sqlDataAdapter2.DeleteCommand.Connection.Close();


主  题:  请教在DataGridView中怎样生成自适应的列宽?

自适应 列宽:

'控制dategrid列宽度函数
    Public Sub SizeColumnsToContent(ByVal dataGrid As DataGrid, ByVal nRowsToScan As Integer)
        Dim Graphics As Graphics = dataGrid.CreateGraphics()
        Dim tableStyle As DataGridTableStyle = New DataGridTableStyle

        Try

            Dim dataTable As DataTable = CType(dataGrid.DataSource, DataTable)

            If -1 = nRowsToScan Then

                nRowsToScan = dataTable.Rows.Count

            Else
                nRowsToScan = System.Math.Min(nRowsToScan, dataTable.Rows.Count)
            End If

            dataGrid.TableStyles.Clear()
            tableStyle.MappingName = dataTable.TableName
            Dim columnStyle As DataGridTextBoxColumn
            Dim iWidth As Integer
            For iCurrCol As Integer = 0 To dataTable.Columns.Count - 1
                Dim dataColumn As DataColumn = dataTable.Columns(iCurrCol)
                columnStyle = New DataGridTextBoxColumn
                columnStyle.TextBox.Enabled = True
                columnStyle.HeaderText = dataColumn.ColumnName
                columnStyle.MappingName = dataColumn.ColumnName
                iWidth = CInt(Graphics.MeasureString(columnStyle.HeaderText, dataGrid.Font).Width)
                Dim dataRow As DataRow
                For iRow As Integer = 0 To nRowsToScan - 1
                    dataRow = dataTable.Rows(iRow)
                    If dataRow(dataColumn.ColumnName) <> Nothing Then
                        Dim iColWidth As Integer = CInt(Graphics.MeasureString(dataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Width)
                        Dim iColHight As Integer = CInt(Graphics.MeasureString(dataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Height)
                        iWidth = CInt(System.Math.Max(iWidth, iColWidth))
                    End If
                Next
                columnStyle.Width = iWidth + 10
                tableStyle.GridColumnStyles.Add(columnStyle)
            Next
            dataGrid.TableStyles.Add(tableStyle)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            Graphics.Dispose()
        End Try
    End Sub


主  题:  WinForm中隐藏Datagrid中的一列,有简单的方法吗? 
我也是用DataGrid.TableStyles[Table].GridColumnStyles[0].Width = 0;这么做的.应该是没有其他的方法了

主  题:  WinForm里面怎么捕获DataGrid的双击事件阿? 


namespace DataGridDoubleClick
{
 using System;
 using System.Drawing;
 using System.Collections;
 using System.ComponentModel;
 using System.Windows.Forms;
 using System.Data;

 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.DataGrid dataGrid1;
  private DataSet myDataSet;
  DateTime gridMouseDownTime;
    private System.Windows.Forms.Label label1;
  
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   InitializeComponent();
   gridMouseDownTime = DateTime.Now;
   SetUp();
  }

  private void SetUp()
  {
   // 用2个Table和1和Relation创建DataSet
   MakeDataSet();
   // 数据绑定
   dataGrid1.SetDataBinding(myDataSet, "Customers");

   //添加样式
   AddCustomDataTableStyle();
  }

  private void MakeDataSet()
  {
   // 创建DataSet.
   myDataSet = new DataSet("myDataSet");
      
   // 创建2个DataTables.
   DataTable tCust = new DataTable("Customers");
   
   // 创建两个列,并添加到第一个表
   DataColumn cCustID = new DataColumn("custID");
   DataColumn cCustName = new DataColumn("custName");
   DataColumn cCurrent = new DataColumn("custCity");
   tCust.Columns.Add(cCustID);
   tCust.Columns.Add(cCustName);
   tCust.Columns.Add(cCurrent);

   // 把tables添加到DataSet.
   myDataSet.Tables.Add(tCust);
   
   
   /* 计算tables.对每个客户,创建DataRow变量 */
   DataRow newRow1;
   
   // 添加记录到 Customers Table.
   for(int i = 1; i < 4; i++)
   {
    newRow1 = tCust.NewRow();
    newRow1["custID"] = (100*i).ToString();
    tCust.Rows.Add(newRow1);
   }

   tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";
   tCust.Rows[1]["custName"] = "net_lover";
   tCust.Rows[2]["custName"] = "http://xml.sz.luohuedu.net/";


   tCust.Rows[0]["custCity"] = "北京";
   tCust.Rows[1]["custCity"] = "上海";
   tCust.Rows[2]["custCity"] = "河南";
  }

  private void AddCustomDataTableStyle()
  {
   DataGridTableStyle ts1 = new DataGridTableStyle();
   ts1.MappingName = "Customers";
   // 设置属性
   ts1.AlternatingBackColor = Color.LightGray;

   // 添加Textbox列样式,以便我们捕捉鼠标事件
   DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custID";
   TextCol.HeaderText = "序号";
   TextCol.Width = 100;

   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custName";
   TextCol.HeaderText = "姓名";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custCity";
   TextCol.HeaderText = "地址";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);
  
    dataGrid1.TableStyles.Add(ts1);
   
  }

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  private void InitializeComponent()
  {
      this.dataGrid1 = new System.Windows.Forms.DataGrid();
      this.label1 = new System.Windows.Forms.Label();
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
      this.SuspendLayout();
      //
      // dataGrid1
      //
      this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;
      this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;
      this.dataGrid1.CaptionVisible = false;
      this.dataGrid1.DataMember = "";
      this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
      this.dataGrid1.Location = new System.Drawing.Point(11, 9);
      this.dataGrid1.Name = "dataGrid1";
      this.dataGrid1.Size = new System.Drawing.Size(368, 144);
      this.dataGrid1.TabIndex = 0;
      this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);
      //
      // label1
      //
      this.label1.Location = new System.Drawing.Point(4, 166);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(383, 23);
      this.label1.TabIndex = 1;
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      this.label1.Click += new System.EventHandler(this.Form1_Click);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(387, 201);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.label1,
                                                                  this.dataGrid1});
      this.Name = "Form1";
      this.Text = "鼠标双击事件的例子";
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
      this.ResumeLayout(false);

    }
  #endregion

  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void TextBoxDoubleClickHandler(object sender, EventArgs e)
  {
   MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
  }

  private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)
  {
   if(DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))
   {
     MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
   }
   label1.Text = "TextBox 鼠标按下了。  ";
  }

  private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
   gridMouseDownTime = DateTime.Now;
   label1.Text = "DataGrid1 鼠标按下了。  ";
  }

    private void Form1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
    private void label1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
 }
}


namespace DataGridDoubleClick
{
 using System;
 using System.Drawing;
 using System.Collections;
 using System.ComponentModel;
 using System.Windows.Forms;
 using System.Data;

 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.DataGrid dataGrid1;
  private DataSet myDataSet;
  DateTime gridMouseDownTime;
    private System.Windows.Forms.Label label1;
  
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   InitializeComponent();
   gridMouseDownTime = DateTime.Now;
   SetUp();
  }

  private void SetUp()
  {
   // 用2个Table和1和Relation创建DataSet
   MakeDataSet();
   // 数据绑定
   dataGrid1.SetDataBinding(myDataSet, "Customers");

   //添加样式
   AddCustomDataTableStyle();
  }

  private void MakeDataSet()
  {
   // 创建DataSet.
   myDataSet = new DataSet("myDataSet");
      
   // 创建2个DataTables.
   DataTable tCust = new DataTable("Customers");
   
   // 创建两个列,并添加到第一个表
   DataColumn cCustID = new DataColumn("custID");
   DataColumn cCustName = new DataColumn("custName");
   DataColumn cCurrent = new DataColumn("custCity");
   tCust.Columns.Add(cCustID);
   tCust.Columns.Add(cCustName);
   tCust.Columns.Add(cCurrent);

   // 把tables添加到DataSet.
   myDataSet.Tables.Add(tCust);
   
   
   /* 计算tables.对每个客户,创建DataRow变量 */
   DataRow newRow1;
   
   // 添加记录到 Customers Table.
   for(int i = 1; i < 4; i++)
   {
    newRow1 = tCust.NewRow();
    newRow1["custID"] = (100*i).ToString();
    tCust.Rows.Add(newRow1);
   }

   tCust.Rows[0]["custName"] = "【孟宪会之精彩世界】";
   tCust.Rows[1]["custName"] = "net_lover";
   tCust.Rows[2]["custName"] = "http://xml.sz.luohuedu.net/";


   tCust.Rows[0]["custCity"] = "北京";
   tCust.Rows[1]["custCity"] = "上海";
   tCust.Rows[2]["custCity"] = "河南";
  }

  private void AddCustomDataTableStyle()
  {
   DataGridTableStyle ts1 = new DataGridTableStyle();
   ts1.MappingName = "Customers";
   // 设置属性
   ts1.AlternatingBackColor = Color.LightGray;

   // 添加Textbox列样式,以便我们捕捉鼠标事件
   DataGridTextBoxColumn TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custID";
   TextCol.HeaderText = "序号";
   TextCol.Width = 100;

   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custName";
   TextCol.HeaderText = "姓名";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);

   TextCol = new DataGridTextBoxColumn();
   TextCol.MappingName = "custCity";
   TextCol.HeaderText = "地址";
   TextCol.Width = 100;
   //添加事件处理器
   TextCol.TextBox.MouseDown += new MouseEventHandler(TextBoxMouseDownHandler);
   TextCol.TextBox.DoubleClick += new EventHandler(TextBoxDoubleClickHandler);
   ts1.GridColumnStyles.Add(TextCol);
  
    dataGrid1.TableStyles.Add(ts1);
   
  }

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  private void InitializeComponent()
  {
      this.dataGrid1 = new System.Windows.Forms.DataGrid();
      this.label1 = new System.Windows.Forms.Label();
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
      this.SuspendLayout();
      //
      // dataGrid1
      //
      this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;
      this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.WindowText;
      this.dataGrid1.CaptionVisible = false;
      this.dataGrid1.DataMember = "";
      this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
      this.dataGrid1.Location = new System.Drawing.Point(11, 9);
      this.dataGrid1.Name = "dataGrid1";
      this.dataGrid1.Size = new System.Drawing.Size(368, 144);
      this.dataGrid1.TabIndex = 0;
      this.dataGrid1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dataGrid1_MouseDown);
      //
      // label1
      //
      this.label1.Location = new System.Drawing.Point(4, 166);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(383, 23);
      this.label1.TabIndex = 1;
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      this.label1.Click += new System.EventHandler(this.Form1_Click);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(387, 201);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                  this.label1,
                                                                  this.dataGrid1});
      this.Name = "Form1";
      this.Text = "鼠标双击事件的例子";
      ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
      this.ResumeLayout(false);

    }
  #endregion

  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void TextBoxDoubleClickHandler(object sender, EventArgs e)
  {
   MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
  }

  private void TextBoxMouseDownHandler(object sender, MouseEventArgs e)
  {
   if(DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime))
   {
     MessageBox.Show("双击事件发生。鼠标双击到的值:"+((TextBox)sender).Text.ToString());
   }
   label1.Text = "TextBox 鼠标按下了。  ";
  }

  private void dataGrid1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
   gridMouseDownTime = DateTime.Now;
   label1.Text = "DataGrid1 鼠标按下了。  ";
  }

    private void Form1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
    private void label1_Click(object sender, System.EventArgs e)
    {
      label1.Text="";
    }
 }
}

主  题:  在C#(winform)中如何设置datagrid某一行的背景色,或字体的颜色啊?高手救命!!


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace DataGridCellFormatting
{
/// <summary>
/// Form2 的摘要说明。
/// </summary>
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form2()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGrid1 = new System.Windows.Forms.DataGrid();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(536, 296);
this.dataGrid1.TabIndex = 0;
this.dataGrid1.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid1_Navigate);
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(560, 389);
this.Controls.Add(this.dataGrid1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);

}
#endregion


private void FormatGridCells(object sender, DataGridFormatCellEventArgs e)
{
//color row 1 red
if(e.Row == 0)
e.BackBrush = Brushes.Red;
if(e.Row == 1)
e.BackBrush = Brushes.Red;
if(e.Row == 2)
e.BackBrush = Brushes.Red;
if(e.Row == 3)
e.BackBrush = Brushes.Red;

//color column 4 blue
//if(e.Column == 4)
//e.BackBrush = Brushes.Blue;
//
set font of some cells to bold
//if( (e.Row + e.Column) % 5 == 0 )
//e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold);
//
set textcolor of some cells to blue
//if( (e.Row + e.Column) % 8 == 0 )
//e.ForeBrush = Brushes.DodgerBlue;
//
set font of some cells to bold, underline, italic with white text on green background
//if( (e.Row + e.Column) % 9 == 0 )
//{
//e.TextFont = new Font(e.TextFont.Name, e.TextFont.Size, FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);
//e.ForeBrush = Brushes.White;
//e.BackBrush = Brushes.Green;
//}


}

private DataTable SomeDataTable()
{
DataTable dt = new DataTable("MyTable");

//add some columns
int nCols = 10;
for(int j = 0; j < nCols; ++j)
dt.Columns.Add(new DataColumn(string.Format("col{0}", j), typeof(string)));

//add some rows
int nRows = 40;
for(int i = 0; i < nRows; ++i)
{
DataRow dr = dt.NewRow();
for(int j = 0; j < nCols; ++j)
dr[j] = string.Format("row {0} col {1}", i, j);
dt.Rows.Add(dr);
}

dt.DefaultView.AllowNew = false;//turn off append row
return dt;
}

private void AddCellFormattingColumnStyles(DataGrid grid, FormatCellEventHandler handler)
{
DataGridTableStyle ts = new DataGridTableStyle();

DataTable dt = (DataTable) grid.DataSource;

ts.MappingName = dt.TableName;

for(int j = 0; j < dt.Columns.Count; ++j)
{
DataGridFormattableTextBoxColumn cs = new DataGridFormattableTextBoxColumn(j);
cs.MappingName = dt.Columns[j].ColumnName;
cs.HeaderText = dt.Columns[j].ColumnName;
cs.SetCellFormat += handler;
ts.GridColumnStyles.Add(cs);
}

grid.TableStyles.Clear();
grid.TableStyles.Add(ts);

}
private void dataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
{

}

private void Form2_Load(object sender, System.EventArgs e)
{
this.dataGrid1.DataSource = SomeDataTable();

AddCellFormattingColumnStyles(this.dataGrid1, new FormatCellEventHandler(FormatGridCells));
}

public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);

public class DataGridFormatCellEventArgs : EventArgs
{
private int _column;
private int _row;
private Font _font;
private Brush _backBrush;
private Brush _foreBrush;
private bool _useBaseClassDrawing;


public DataGridFormatCellEventArgs(int row, int col, Font font1, Brush backBrush, Brush foreBrush)
{
_row = row;
_column = col;
_font = font1;
_backBrush = backBrush;
_foreBrush = foreBrush;
_useBaseClassDrawing = false;
}

public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Font TextFont
{
get{ return _font;}
set{ _font = value;}
}

public Brush BackBrush
{
get{ return _backBrush;}
set{ _backBrush = value;}
}
public Brush ForeBrush
{
get{ return _foreBrush;}
set{ _foreBrush = value;}
}
public bool UseBaseClassDrawing
{
get{ return _useBaseClassDrawing;}
set{ _useBaseClassDrawing = value;}
}
}

public class DataGridFormattableTextBoxColumn : DataGridTextBoxColumn
{
//in your handler, set the EnableValue to true or false, depending upon the row & col
public event FormatCellEventHandler SetCellFormat;

private int _col;

public DataGridFormattableTextBoxColumn(int col)
{
_col = col;
}

protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, this._col, this.DataGridTableStyle.DataGrid.Font, backBrush, foreBrush);
if(SetCellFormat != null)
{
SetCellFormat(this, e);
}
if(e.UseBaseClassDrawing)
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
else
{
g.FillRectangle(e.BackBrush, bounds);
g.DrawString(this.GetColumnValueAtRow(source, rowNum).ToString(), e.TextFont, e.ForeBrush, bounds.X, bounds.Y);
}
if(e.TextFont != this.DataGridTableStyle.DataGrid.Font)
e.TextFont.Dispose();
}

protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//comment to make cells unable to become editable
base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}

}
}
}


只需要改变FormatGridCells中的行就行了

主  题:  如何让WINFORM的DATAGRID控件的列有的为只读属性,有的不是只读属性 

1、手工:Datagrid->属性->TableStyles->GridCoumnStyles

2、代码:this.dataGrid1.TableStyles["tablename"].GridColumnStyles["ID"].ReadOnly = true;


this.dataGrid1.TableStyles["tablename"].GridColumnStyles["ID"].ReadOnly = true;

显示和隐藏DataGrid中的列

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="ShowHideCols.aspx.vb"
Inherits="aspxWeb.ShowHideCols"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>ShowHideCols</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
      <asp:Button ID="btnShow" Text="Show Details" OnClick="ShowDetails" Runat="server" />
      <asp:Button ID="btnHide" Text="Hide Details" OnClick="HideDetails" Runat="server" />
      <asp:DataGrid ID="dtgCusts" Runat="server" AutoGenerateColumns="False"
    BorderColor="#999999" BorderStyle="None" BorderWidth="1px" BackColor="White"
     CellPadding="3" GridLines="Vertical">
        <Columns>
          <asp:BoundColumn DataField="Title" />
          <asp:BoundColumn DataField="id" Visible="False" />
          <asp:BoundColumn DataField="CreateDate" DataFormatString="{0:yyyy-MM-dd HH:mm:ss}"
     Visible="False" />
            <asp:EditCommandColumn EditText="Edit" HeaderText="Edit" Visible="False" />
        </Columns>
        <AlternatingItemStyle BackColor="#DCDCDC" />
        <ItemStyle ForeColor="Black" BackColor="#EEEEEE" />
        <headerStyle Font-Bold="True" ForeColor="White" BackColor="#000084" />
      </asp:DataGrid>
    </form>
  </body>
</HTML>

Imports System.Data
Imports System.Data.OleDb

Public Class ShowHideCols
  Inherits System.Web.UI.Page
  Protected WithEvents btnShow As System.Web.UI.WebControls.Button
  Protected WithEvents btnHide As System.Web.UI.WebControls.Button
  Protected WithEvents dtgCusts As System.Web.UI.WebControls.DataGrid

#Region " Web 窗体设计器生成的代码 "

  '该调用是 Web 窗体设计器所必需的。
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_
   Handles MyBase.Init
    'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
    '不要使用代码编辑器修改它。
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
   Handles MyBase.Load
    '在此处放置初始化页的用户代码
    btnShow.Text = "显示列"
    btnHide.Text = "隐藏列"
    dtgCusts.Columns(1).HeaderText = ""
    dtgCusts.Columns(0).HeaderText = "标题"
    dtgCusts.Columns(2).HeaderText = "发布日期"
    dtgCusts.Columns(3).HeaderText = "编辑"
    If Not IsPostBack Then
      BindTheData()
    End If
  End Sub

  Sub BindTheData()
    Dim objConn As OleDbConnection
    Dim objCmd As OleDbCommand
    objConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
 + Server.MapPath("Test.mdb"))
    Dim strSql As String
    strSql = "SELECT Top 10 id,Title,CreateDate FROM Document"
    objCmd = New OleDbCommand(strSql, objConn)
    objConn.Open()
    dtgCusts.DataSource = objCmd.ExecuteReader()
    dtgCusts.DataBind()
    objConn.Close()
    objConn.Dispose()
  End Sub
  Sub ShowDetails(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim intCounter As Integer
    For intCounter = 1 To dtgCusts.Columns.Count - 1
      dtgCusts.Columns(intCounter).Visible = True
    Next
  End Sub

  Sub HideDetails(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim intCounter As Integer
    For intCounter = 1 To dtgCusts.Columns.Count - 1
      dtgCusts.Columns(intCounter).Visible = False
    Next
  End Sub

End Class


主  题:  请教在DataGridView中怎样生成自适应的列宽?
你可以用下面的方法实现:
private void gridView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
int a=e.X/colKeyWords.Width;
int b=(e.Y+10)/colKeyWords.Width-3;
if(a>=0 && b>=0 && a<dataSet11.Tables["BugMan"].Columns.Count && b<dataSet11.Tables["BugMan"].Rows.Count)
         toolTipController1.SetToolTip(gridControl1,dataSet11.Tables["BugMan"].Rows[b].ItemArray[a].ToString());
}
我用的是tooltip,colkeywords.width是某一个列的长度

转载于:https://www.cnblogs.com/friendwang1001/archive/2006/02/19/333463.html

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值