【问题标题】:How to get data from a cell in DataGrid如何从 DataGrid 中的单元格中获取数据
【发布时间】:2012-05-09 00:43:30
【问题描述】:

您好,我有一个数据网格,其中包含带有复选框的列。我想在特定条件下禁用该复选框。我有一个 SQL DB,我从中得到一个 DataSet,然后我在 Data Grid 中填充数据集。这是我的一些代码

    Dim loopRow As Integer = ds.Tables(0).Rows.Count - 1
        Dim ColDS As New DataColumn("Status")
        ds.Tables(0).Columns.Add(ColDS)
        For loopval As Integer = 0 To loopRow
            If ds.Tables(0).Rows(loopval)(8).ToString = "True" Then
                ds.Tables(0).Rows(loopval)(11) = "Confirmed"
            Else
                ds.Tables(0).Rows(loopval)(11) = "Pending"
            End If
        Next
        For loopDate As Integer = 0 To ds.Tables(0).Rows.Count - 1
            If ds.Tables(0).Rows(loopDate)("ProgramTours_FromDate") <= Now.Date Then

            End If
        Next
        GrdAgentBL.DataSource = ds
        GrdAgentBL.DataBind()

【问题讨论】:

  • 条件是 Tour From Date 如果它小于现在日期,那么它将禁用数据网格中名为 Confirmed 的列,其中包含一个复选框。如果满足条件,我需要禁用该列

标签: vb.net datagrid


【解决方案1】:

这里是代码

 For Each Item As DataGridItem In GrdAgentBL.Items 'load the items first
                Dim lblTemp As New Label 'My Data is stored in a label
                lblTemp = Item.Cells(2).Controls(1) 'So I take it inside that new label
                Dim tx As String = lblTemp.Text 'Then I load it on the Tx var
                If tx <= Now.Date Then 'if it's meet the condition we will disable the column
                    Item.Cells(11).Enabled = False
                End If
 Next

【讨论】:

  • 如果是这种情况,为什么不能比较这个值并从 db 获取布尔值? Getdate() 等函数返回今天的日期。因此,您可以根据条件简单地启用或禁用网格。
  • 感谢您的回答。我不确定这些行何时执行。一些发现后会更新你
  • 我可以知道使用 rawdatabound 和你的方法有什么区别吗?
  • 首先我在数据集中有数据,所以我不想再次连接到数据库。在数据集中我有我需要的所有值,所以我不需要获取其他数据。这些行在网格中的列值满足条件时执行。该列有一个日期,该日期表明该人是否可以在该时间取消。
  • 没错,我从数据网格内部检查数据,然后应用业务逻辑。
【解决方案2】:

我认为这是您查询的解决方案。

//I am setting dataTable using this function  
Private Sub setDataTable()
        Dim dt As DataTable
        dt = New DataTable()
        dt.Columns.Add("Name")
        dt.Columns.Add("Val")
        Dim dr As DataRow = dt.NewRow()
        dr("Name") = "Abcd"
        dr("Val") = 1
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr("Name") = "xyz"
        dr("Val") = 2
        dt.Rows.Add(dr)
        grdView.AutoGenerateColumns = False
        grdView.DataSource = dt
        grdView.DataBind()

    End Sub

// This code will do enabling or disabling the checkbox.
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView grdRow = (DataRowView)e.Row.DataItem;
            if (grdRow.Row.ItemArray[1].ToString() == "1")
            {
                e.Row.Enabled = false;
            }

        }

最佳实践:请从 SQL 形成您的数据表。使用一个简单的案例并在您的代码中排除此循环。所以如果可能有 1000 行,你需要迭代 1000 行。

select val1,val2,(case when val1=0 then 1 else 0 end) as val3 from tbl.

所以这可能比任何迭代都更快

【讨论】:

  • 这是一个很好的答案,但我会再给你一个
猜你喜欢
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
相关资源
最近更新 更多