asp.NetGridView共通コード集錦

2426 ワード

1.GridView汎用UpdateSQL生成関数に対して、単一テーブルに対して有効
public bool GetUpdateRow(GridView gv, int RowIndex,out DALDataRow drRow,out DALDataRow drKeys)
{
    drRow = GetDataRow(gv, RowIndex);
    drKeys = GetDataKeys(gv, RowIndex);
    if (drRow == null||drKeys==null)
    {
        return false;
    }//if
    return true;
}
private DALDataRow GetDataKeys(GridView gv, int RowIndex)
{
    DALDataRow drKeys = new DALDataRow();
    var KeyNames = gv.DataKeyNames;
    var Keys = gv.DataKeys[RowIndex].Values;
    for( int i=0; i<KeyNames.Length;i++)
    {
        drKeys.Add(KeyNames[i].ToLower(), Keys[i].ToString());
    }//for( int i=
    return drKeys;
}
public DALDataRow GetDataRow(GridView gv,int RowIndex)
{
    List<string> DataFields = new List<string>();
    List<string> Values = new List<string>();
    DALDataRow dr = new DALDataRow();
    foreach (DataControlField c in gv.Columns)
    {
        if (c is BoundField)
        {
            DataFields.Add(((BoundField)c).DataField.ToString().ToLower());
        }
        if (c is TemplateField)
        {
            TemplateField t = c as TemplateField;
            
        }
    }
    foreach (TableCell r in gv.Rows[RowIndex].Cells)
    {
        if (r.Controls[0] is TextBox)
        {
            Values.Add(((TextBox)(r.Controls[0])).Text);
        }
    }
    if (DataFields.Count!=Values.Count
        ||DataFields.Count < 1)
    {
        return null;
    }//if
    for (int i = 0; i < DataFields.Count;i++ )
    {
        dr.Add(DataFields[i], Values[i].ToString());
    }//for
    return dr;
}

2.GridViewは数行ごとに空行を増やす方法(回転)
文章のリストには、5行か10行の下に空行があることがよく見られます.これにより、サイトの内容を読むと、あまり抑圧的ではありませんが、このGridViewもできます.
//1.  GridView   OnRowDataBound  ,  :OnRowDataBound="gv_RowDataBound"
//2.  gv_RowDataBound     :
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
	if   (e.Row.RowIndex   > 0   &&     (e.Row.RowIndex+1)   %   5   ==   0)         
	{ 
		GridViewRow newRow = new GridViewRow(0,0,DataControlRowType.DataRow,DataControlRowState.Normal);     
		newRow.Cells.Add(new   TableCell());                      
		newRow.Cells[0].ColumnSpan   =   e.Row.Cells.Count;                    
		newRow.Cells[0].Text   =   "  ";                       
		this.gv.Controls[0].Controls.Add(newRow);             
	} 
}