前段时间做项目做项目,需要记录checkboxlist选中的内容,并转换成表格。写了个方法,与大家分享!
首先将checkboxlist被选中的内容转换成一个二维数组,这部分写的不太好,大家有没有更好的方法?
然后二维数组转换成DataTable
首先将checkboxlist被选中的内容转换成一个二维数组,这部分写的不太好,大家有没有更好的方法?
protected void NewString(){
string[,] str = new string[this.cblist.Items.Count, 2];
//cblist行计数器
int k = 0;
for (int i = 0; i < cblist.Items.Count; i++)
{
//记录cblist被选中内容(但在k不等于cblist.Items.Count时数组会出现多个null值)
if (cblist.Items[i].Selected)
{
//二维数组列循环
for (int j = 0; j <= 1; j++)
{
if (j != 1)
{ str[k, j] = this.cblist.Items[i].Value;}
else
str[k, j] = this.cblist.Items[i].Text;
}
k++;
}
}
//截断null值
string[,] strtemp = new string[k, 2];
for (int b = 0; b < k; b++)
{
for (int h = 0; h < 2; h++)
{
strtemp[b, h] = str[b, h];
}
}
}
然后二维数组转换成DataTable
protected DataTable StrToDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));
//表格行循环
for (int row = 0; row < strtemp.GetLength(0); row++)
{
DataRow dr = dt.NewRow();
//表格列循环
for (int col = 0; col < 2; col++)
{
dr[col] = strtemp[row, col].ToString();
}
//将行添加到表格中
dt.Rows.Add(dr);
}
return dt;
}