當前位置:開發者網絡 >> 技術教程 >> .NET教程 >> 數據庫應用 >> 內容
精彩推薦
分類最新教程
分類熱點教程
    
DataGrid相關知識總結(收集)
作者:未知
日期:2005-03-23
人氣:
投稿:snow(轉貼)
來源:未知
字體:
收藏:加入瀏覽器收藏
以下正文:
關於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是某一個列的長度




相關文章: