2017/01/25

[C#] GridView to Datatable

#region GridView to Datatable 
DataTable dt = new DataTable("Test");//Create a new DataTable. 
foreach (TableCell cell in GridView.HeaderRow.Cells)
{       dt.Columns.Add(cell.Text);//Add columns to DataTable.
} 

//Loop through the GridView and copy rows.
foreach (GridViewRow row in GridView.Rows)
{       if (row.RowType == DataControlRowType.DataRow)
        {      dt.Rows.Add(); 

                CheckBox myCheckBox = row.FindControl("CheckBox") as CheckBox;
                dt.Rows[row.RowIndex]["Expired"] = myCheckBox.Checked.ToString();

                Label Label_KEYID = row.FindControl("Label_KEYID") as Label;
                dt.Rows[row.RowIndex]["Key ID"] = Label_KEYID.Text;

                Label Label_ID = row.FindControl("Label_ID") as Label;
                dt.Rows[row.RowIndex]["ID"] = Label_ID.Text;
        }
}
#endregion

沒有留言: