C#/ASP.Net-提取gridview中列的位值
我有一个绑定SQL的gridview。在某些列中有位值。当我使用C#将值输入gridview时,会显示复选框。我需要将该列的值提取到文本中C#/ASP.Net-提取gridview中列的位值,asp.net,stored-procedures,gridview,bit,ordinal,Asp.net,Stored Procedures,Gridview,Bit,Ordinal,我有一个绑定SQL的gridview。在某些列中有位值。当我使用C#将值输入gridview时,会显示复选框。我需要将该列的值提取到文本中 SqlConnection sConnection = new SqlConnection(MyConnectionString); SqlCommand sCommand = new SqlCommand(); using (sConnection) { sCommand.Connection = sConn
SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
{
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}
概述:
- 您需要能够找到生成的复选框并获取其“Checked”属性的值
- 为此,您需要能够在GridViewRow上使用FindControl()方法
- 要使用FindControl,复选框需要一个可预测的名称
- 要获得可预测的名称,需要将该列设置为TemplateColumn,以便可以在ASPX页面的标记中指定复选框的名称
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="MyColumnNameCheckbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
我能弄明白。谢谢,大卫·斯特拉顿,为我指明了正确的方向。 我首先为动态创建的控件分配了一个id。然后FindControl()执行了 这将返回一个值“True”或“False”
再次感谢。另一种解决方法:
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();
它用更少的代码解决了这个问题:)我试着按照你的建议去做。但是,gridview是动态创建的。我尝试为gridview单元格中的控件指定一个名称,并使用FindControl()方法。它返回null。基本上,我只需要找到一种从gridview获取(位)值的方法。如果我尝试将其作为字符串返回,则返回null。似乎应该有一个简单的方法来做到这一点。
string defaultvalue = "0"; // To be used to display the value of the original bit field.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox");
if (chkBx != null && chkBx.Checked)
{
defaultvalue = "1";
}
}
Control ctrl = GridView1.SelectedRow.Cells[4].Control[0];
ctrl.ID = "ctrl";
Boolean result = Convert.ToBoolean(((Checkbox)GridView1.Rows[0].Cells[4].FindControl("ctrl")).Checked);
TextBox1.Text = result.ToString();
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();