根据vb.net中数据表的另一个列值获取列值

时间:2013-09-02 09:30:51

标签: vb.net vb.net-2010

我有一个类似于此的数据表:

id msg 1谢谢.. 2亲切...... 3请插入.. 4请停止

我需要根据数据表中的特定id获取一个msg,这就是我填充数据表的方式:

msgTable = selectMsg()
MsgBox(i need to get the msg here)

   Public Function selectMsg() As DataTable
    Dim command As SqlCommand = New SqlCommand("selectMsg", cn)
    command.CommandType = CommandType.StoredProcedure
    Dim da As New SqlDataAdapter(command)
    'If dt.Rows.Count <> 0 Then
    '    dt.Rows.Clear()
    'End If
    Try
        da.Fill(msgDS, "N_AI_HOME_CARE")
        msgDT = msgDS.Tables(0)
    Catch ex As Exception
        logFile("SP selectMsg ---" + ex.Message)
    End Try
    Return msgDT
End Function

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:1)

假设您的存储过程返回消息的整个数据表(非常糟糕的移动,因为如果表很大,您可能会遇到性能和网络问题),那么您需要将Select method with a filter expression应用于返回的数据表< / p>

msgTable = selectMsg()
Dim rows() = msgTable.Select("ID = " & idOfMessage)
if rows.Length > 0 then
    MsgBox(row(0)(1).ToString()) ' read the first row, second column of the table'
End If

但我认为你应该使用一个更简单的ExecuteScalar来更正确的方法,它不会返回整个数据表但只返回查询的第一行和第一列

Public Function selectMsg(idOfMessage as Integer) As String
    Dim command As SqlCommand = New SqlCommand("SELECT msg from tableName where ID = @id", cn)
    command.Parameters.AddWithValue("@id", idOfMessage)
    Dim result = command.ExecuteScalar()
    if string.IsNullOrEmpty(result) Then
        result = "No message found"
    End If
    return result
End Function

答案 1 :(得分:0)

实际上,我发现你使用

MsgBox(msgTable.Rows(0)(1).ToString()) 

没有任何选择方法:)