如果我的gridview中的数据被检查,我有这个方法循环,如果选中它们,它们应该被插入到数据库中。 正如您所看到的,我想从gridview中插入的唯一数据是gridview中单元格[2]中的文本,它的名称为 @HeaderName
using (SqlConnection con = new SqlConnection("my con string"))
{
con.Open();
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Accounting_Consolidation_ServiceOutputs(Cusomer_Name, Service_Name, Header_Name, Sort_Postion, Rename_to, Value) Values(@CustName,@ServiceName,@HeaderName,@Sort,@Rename,@Value)", con))
{
//cmd.Parameters.AddWithValue("PersonId", Convert.ToInt32(GridViewConsNames.DataKeys[row.RowIndex].Value));
cmd.Parameters.AddWithValue("@CustName", TextBoxCustName.Text);
cmd.Parameters.AddWithValue("@ServiceName", DropDownListServicesAvailable2.SelectedItem.Text);
cmd.Parameters.AddWithValue("@HeaderName", "Name of the checked cells from my gridview");
cmd.Parameters.AddWithValue("@Sort", null);
cmd.Parameters.AddWithValue("@Rename", "");
cmd.Parameters.AddWithValue("@Value", null);
cmd.ExecuteNonQuery();
}
}
}
}
我试过这个
GridViewRow row = GridViewConsNames.SelectedRow;
string headername = row.Cells[2].Text;
但这似乎不起作用
答案 0 :(得分:1)
为什么在实际想要使用选中复选框的所有行时使用GridViewRow row = GridViewConsNames.SelectedRow
?
所以我想这就是你想要的:
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
// ...
string headerName = row.Cells[2].Text;
cmd.Parameters.AddWithValue("@HeaderName", headerName);
// ...
}
}