批量獲取DataGrid控件模板列中的數據
2024-07-21 02:22:54
供稿:網友
批量獲取datagrid控件模板列中的數據
在datagrid中一般只能單個獲取每一行的數據,若要批量獲取datagrid控件中的數據必須對每一個模板列的控件進行掃描,獲取其中的數據。
我本想做的程序是根據不同的行數,由用戶一次輸入若干數據,提交后系統自動獲取批量數據的程序。
以下程序簡單表達了需要實現的功能
test.aspx
..........
<asp:datagrid id="dgresult" runat="server" bordercolor="#deba84" borderstyle="none" cellspacing="2"
borderwidth="1px" backcolor="#deba84" cellpadding="3" autogeneratecolumns="false">
<footerstyle forecolor="#8c4510" backcolor="#f7dfb5"></footerstyle>
<selecteditemstyle font-bold="true" forecolor="white" backcolor="#738a9c"></selecteditemstyle>
<itemstyle forecolor="#8c4510" backcolor="#fff7e7"></itemstyle>
<headerstyle font-bold="true" forecolor="white" backcolor="#a55129"></headerstyle>
<columns>
<asp:boundcolumn datafield="id" headertext="列號"></asp:boundcolumn>
<asp:templatecolumn headertext="列名">
<itemtemplate>
<asp:textbox runat="server" enabled="true" width="50" id="col"></asp:textbox>
</itemtemplate>
</asp:templatecolumn>
<asp:templatecolumn headertext="整數精度">
<itemtemplate>
<asp:textbox runat="server" enabled="true" id="textbox1" width="50">20</asp:textbox>
</itemtemplate>
</asp:templatecolumn>
<asp:templatecolumn headertext="小數點精度">
<itemtemplate>
<asp:textbox runat="server" enabled="true" id="textbox2" width="50">10</asp:textbox>
</itemtemplate>
</asp:templatecolumn>
</columns>
<pagerstyle horizontalalign="center" forecolor="#8c4510" mode="numericpages"></pagerstyle>
</asp:datagrid>
<asp:button id="btnok" runat="server" text="提交"></asp:button>
......
test.aspx.cs
private void page_load(object sender, system.eventargs e)
{
// 在此處放置用戶代碼以初始化頁面
if(!ispostback)
mfbind(datasource());
}
private ilist datasource()
{
datatable dt=new datatable();
datacolumn dc=new datacolumn();
dc.columnname="id";
dc.datatype=system.type.gettype("system.int32");
dc.readonly=true;
dc.unique=true;
dc.autoincrement=true;
dc.autoincrementseed=0;
dc.autoincrementstep=1;
dt.columns.add(dc);
dc=new datacolumn();
dc.columnname="列名稱";
dc.datatype=system.type.gettype("system.string");
dt.columns.add(dc);
for(int i=0;i<10;i++)
{
datarow dr=dt.newrow();
dr[1]=i;
dt.rows.add(dr);
}
session["source"] = dt;
return dt.defaultview;
}
private void mfbind(ilist dv)
{
this.dgresult.datasource=(dataview)dv;
this.dgresult.databind();
}
private void btnok_click(object sender, system.eventargs e)
{
//string tmpa=dgresult__ctl2_col1.text;
textbox txt;
arraylist marr=new arraylist();
for(int i=0;i<10;i++)
{
txt=new textbox();
txt=(textbox)dgresult.items[i].findcontrol("col");
marr.add(txt.text);
}
for(int i=0;i<marr.count;i++)
this.lblproblem.text+=marr[i].tostring()+" ; ";
}
其實這樣的程序有共通性,通過datagrid控件可以對數據進行批量處理,特別是對刪除數據等操作的過程中使用起來及其方便快捷,只要將程序的模板列中的textbox控件改為checkbox控件或者dropdownlist控件,掃描所有的子控件就可以實現對數據的批量快速刪除、修改等操作。