asp.net - C#/ASP.Net - 提取 GridView 中列的位值

标签 asp.net stored-procedures gridview bit ordinal

我有一个 SQL 绑定(bind)的 gridview。在某些列中存在位值。当我使用 C# 将值获取到 gridview 时,会显示复选框。我需要将该列的值提取到文本中。

    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);
            }
        }
    }

gridview 列数据类型为“bit”。我无权访问数据库或存储过程来更改其中的任何内容。我需要以某种方式提取“0”或“1”值,但是当我像上面那样做时,文本是空白的。

我还尝试使用“GetOrdinal”。它从数据库返回一个 True/False 值,但我不知道如何获取 gridview 中每个项目的值。

    if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))
    {
        ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
    }

最佳答案

总体概述:

  • 您需要能够找到生成的 CheckBox 并获取其“Checked”属性的值。

  • 为此,您需要能够在 GridViewRow 上使用 FindControl() 方法。

  • 要使用 FindControl,CheckBox 需要一个可预测的名称。
  • 要获得可预测的名称,您需要将该列设置为 TemplateColumn,以便您可以在 ASPX 页面的标记中指定复选框的名称。

这里有完整的工作代码集:http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater

这显示了 Repeater 的代码,但它与任何 DataBound 控件的原理和通用代码相同。

下面的代码应该可以进行修改以匹配您的数据库名称:

 <asp:TemplateField> 
   <ItemTemplate > 
       <asp:checkbox id="MyColumnNameCheckbox" runat="server" /> 
   </ItemTemplate> 
 </asp:TemplateField> 

    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";
        } 
    } 

关于asp.net - C#/ASP.Net - 提取 GridView 中列的位值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12376864/

相关文章:

javascript - 如何禁用 GridView 中的 LinkBut​​ton

asp.net - 如何将 Visual Studio 中的本地文件添加到 Azure LocalResource "folder"?

c# - 登录并将授权属性添加到操作后无法访问 Controller 操作

sql - 列数 每个过程返回 T-Sql

c# - 如何在没有选择按钮的情况下在 GridView 中实现全行选择?

c# - asp.net gridview 中的分页和排序问题

asp.net - 为什么元素在 jquery 中为 null,但在 document.getelementbyid() 中却存在

c# - 将数据从 Html.Action 传递到局部 View

mysql - 在 MySQL 存储过程中检查局部变量是否为 null

django - 存储过程结果到 Django 模型