循环以便在C#中读取数据网格视图的几行
本文关键字:视图 几行 网格 数据网 数据 读取 循环 | 更新日期: 2023-09-27 18:28:38
我有一个数据网格(grid_detail),因为现在我只读取了其中的一行,并使用下面的代码保存到数据库中
//number of columns actually in second dgv
int col_no = grid_detail.ColumnCount;
int row_no = grid_detail.RowCount - 1;
int r = 0;
//array to contain the values of the cells
string[] col_value = new string[100];
for (i = 0; i < col_no; i++)
{
//fill in the Array with values from cells
col_value[i] = Convert.ToString(grid_detail.Rows[0].Cells[i].Value);
}
//Build insert command
StringBuilder Q = new StringBuilder();
Q.Append("INSERT INTO ");
Q.Append("[Ref].[");
Q.Append(_lstview_item);
Q.Append("]");
Q.Append(" VALUES");
Q.Append("(");
for (i = 0; i < col_no; i++)
{
Q.Append("'");
if (string.IsNullOrEmpty(col_value[i]))
{
x = false;
break;
}
else
{
Q.Append(col_value[i]);
Q.Append("'");
Q.Append(",");
x = true;
}
}
//removing last COMMA from loop
if (col_no > 0)
{
Q.Length--;
}
Q.Append(")");
query = Q.ToString();
if (x == true)
{
//open connection to db and send query
SqlConnection conn = new SqlConnection(cc.connectionString(cmb_dblist.Text));
SqlCommand cmd_server = new SqlCommand(query);
cmd_server.CommandType = CommandType.Text;
cmd_server.Connection = conn;
conn.Open();
cmd_server.ExecuteNonQuery();
conn.Close();
然而,我的要求是,我现在读取不止一行z网格并保存到数据库中。我试着用for循环来计算像这样的行数
for (r=0;r<row_no;r++)
{
/////CODES ABOVE PASTED HERE
}
我不能做这个循环。
请帮忙。
我假设您已经根据grid_detail行计数设置了row_no
,然后进行以下更改并测试
for (int r=0; r< grid_detail.RowCount; r++)
{
// your code...
//int r = 0; comment this line
// your code...
//.............
for (i = 0; i < col_no; i++)
{
//fill in the Array with values from cells
col_value[i] = Convert.ToString(grid_detail.Rows[r].Cells[i].Value); // use row r
}
//.............
// your code...
}
但我会重新考虑你的代码低于
foreach (GridViewRow row in GridView1.Rows)
{
string sql = GenerateSql(row);
if (!string.IsNullOrEmpty(sql))
ExecuteNonQuery(sql);
}
private void ExecuteNonQuery(string query)
{
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd_server = new SqlCommand(query, conn))
{
conn.Open();
cmd_server.ExecuteNonQuery();
}
}
private string GenerateSql(GridViewRow row)
{
var values = row.Cells.Cast<TableCell>().Select(x => x.Text).ToArray();
if (values.Any(string.IsNullOrEmpty))
{
return string.Empty;
}
var sql = string.Format("INSERT INTO [Ref].[{0}] VALUES ({1})", _lstview_item, string.Join(",", values));
return sql;
}