關于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是某一個列的長度