如何在DataGrid里面使用動(dòng)態(tài)圖形表示數(shù)字
2024-07-21 02:23:35
供稿:網(wǎng)友
本文將要簡(jiǎn)單的介紹如何在datagrid里面用圖形表是一個(gè)數(shù)字,聽(tīng)起來(lái)好象要用到gui的編程,其實(shí)不然,如果你讀完全文你就會(huì)發(fā)現(xiàn)其實(shí)很簡(jiǎn)單,只是一個(gè)“小把戲”而已,但是請(qǐng)不要失望,其實(shí)在實(shí)際的應(yīng)用中這個(gè)“小把戲”就是你項(xiàng)目中的一個(gè)亮點(diǎn)。
首先為了實(shí)現(xiàn)這個(gè)功能我們需要一個(gè)datagrid,并且為這個(gè)datagrid邦定數(shù)據(jù),具體的邦定代碼如下(由于我說(shuō)明問(wèn)題的重點(diǎn)不在如何邦定datagrid所以我就是用了最原始的邦定方法,目的旨在說(shuō)明主題)。
畫(huà)一個(gè)datagrid在html里面,代碼就像下面的一樣,我使用了一個(gè)測(cè)試的數(shù)據(jù)庫(kù)和一個(gè)測(cè)試的表名字都叫test,同時(shí)這個(gè)test表里面有a,b,c3個(gè)字段:
<asp:datagrid id="datagrid1" runat="server" width="100%" autogeneratecolumns="false">
<columns>
<asp:boundcolumn datafield="a" headertext="名稱"></asp:boundcolumn>
<asp:templatecolumn headertext="數(shù)字的圖形表示">
<itemtemplate>
<asp:label id="label1" runat="server"></asp:label>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn datafield="c" headertext="數(shù)字表示"></asp:boundcolumn>
</columns>
</asp:datagrid>
正如你看到的,我們使用了一個(gè)模版列來(lái)顯示數(shù)據(jù),它只是一個(gè)label而不是image,其他兩個(gè)是邦定字段,c就是我們要顯示的數(shù)字了。
ok,接下來(lái)我們看看,cs的部分,幫定代碼如下:
sqlconnection conn = new sqlconnection(system.configuration.configurationsettings.appsettings["connectionstring"]);
sqldataadapter da = new sqldataadapter("select a,c from test",conn);
dataset ds = new dataset();
da.fill(ds);
this.datagrid1.datasource = ds.tables[0];
this.datagrid1.databind();
非常簡(jiǎn)單。因?yàn)槲也幌矚g將數(shù)據(jù)邦定代碼寫(xiě)在html里面所以我使用了itemdatabound事件來(lái)完成這件事情。具體的代碼如下:
private void datagrid1_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e) {
if(e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem){
label lbl = (label)e.item.cells[1].findcontrol("label1");
lbl.text = "<hr align='left' color='blue' size='10' width='"+e.item.cells[2].text+"'>";
}
}
看上去是不是很簡(jiǎn)單?呵呵,希望你不會(huì)以為我在騙你,好了按照上面的步驟創(chuàng)建一個(gè)頁(yè)面試一試吧,效果不錯(cuò),我想通過(guò)他還可以實(shí)現(xiàn)其他很多有關(guān)數(shù)據(jù)的顯示,比如:比例。不過(guò)這種比例的計(jì)算你最好在邦定之前處理好放到datatable里面,這樣邦定的代碼將非常簡(jiǎn)單。運(yùn)行的結(jié)果如下:
好了!此文已完,祝大家工作順利!
:p