获取数据表中的值指数

获取数据表中的值指数

本文介绍了获取数据表中的值指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到一个价值指数在数据表。

i need to get index of a value in DataTable.

我试图让这样的。

 SqlDataAdapter da = new SqlDataAdapter("SELECT MessageID,SenderID,MessageContent FROM Messages WHERE ThreadID="+ThreadID, connectionString);
 //Get all messages in the Thread.
 DataTable dt = new DataTable();
 da.Fill(dt);

 da.SelectCommand.CommandText = "SELECT MessageID,SenderID,MessageContent FROM Messages WHERE MessageID="+MessageID;
 //Get the message which i need to get index.
 DataTable dtMsg = new DataTable();
 da.Fill(dtMsg);
 //Get index of dtMsg.Rows[0] in dt.
 int msgIndex = dt.Rows.IndexOf(dtMsg.Rows[0]);

我analized它时,调试值相同,但其返回-1每次。
我该怎么办?

I analized it when debugging values are same but its returning -1 everytime.What i can do?

推荐答案

您正在寻找在数据表DT行时该行实际上是在数据表dtMsg ....

You are looking for a row in datatable dt when the row is actually in datatable dtMsg....

尝试:

int msgIndex = dtMsg.Rows.IndexOf(dtMsg.Rows[0]);

其实这总是会返回零反正你是用索引引用无论如何行。

Actually that is always going to return zero anyway as you are referencing the row by index anyway.

如果你真正想要的是DT找到一排基于在dtMsg行中的值,你需要使用像查找()或选择()。

If what you actually want is to find a row in dt based on a value in a dtMsg row you will need to use something like Find() or Select().

继承人是一些示例code:

Heres's some sample code:

        // Create test data table with messageid as primary column
        DataTable dt = new DataTable();
        dt.Columns.Add("MessageID", typeof (int));
        dt.Columns.Add("SenderID", typeof(int));
        dt.Columns.Add("MessageContent", typeof(string));
        dt.PrimaryKey = new[] {dt.Columns["MessageID"]};

        // Add some data
        dt.Rows.Add(1, 10, "Message1");
        dt.Rows.Add(2, 11, "Message2");
        dt.Rows.Add(3, 12, "Message3");
        dt.Rows.Add(4, 13, "Message4");

        // Create second test data table with single row
        DataTable dtMsg = new DataTable();
        dtMsg.Columns.Add("MessageID", typeof(int));
        dtMsg.Columns.Add("SenderID", typeof(int));
        dtMsg.Columns.Add("MessageContent", typeof(string));
        dtMsg.PrimaryKey = new[] { dtMsg.Columns["MessageID"] };

        dtMsg.Rows.Add(3, 12, "Message3");

        // Not very elegant way of getting the message id from dtMsg.
        int messageId = (int)dtMsg.Rows[0][0];

        int index = dt.Rows.IndexOf(dt.Rows.Find(messageId));

        // Result : index is 2
        Console.WriteLine(index);

这个假设的MessageId是餐桌上的主索引。

This assumes that MessageId is the primary index on the table.

这篇关于获取数据表中的值指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:12