关于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 [email protected]";
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是某一个列的长度