2

i need to get index of a value in DataTable.

I'm trying to get like that.

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

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

timu
  • 828
  • 7
  • 20
  • 40

1 Answers1

7

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

Try:

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.

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().

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

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

LaughingJohn
  • 114
  • 4
  • No i get all messages on first query on second query i get one message. dt including all messages. dtMsg including only one row which i need to get index. im trying to find in dt not dtMsg – timu Aug 18 '10 at 11:46
  • 1
    So in dtMsg you have one message and you need to find the corresponding index of that message in dt, Is that correct? If so you need to use find or select on dt using the MessageID value from your row in dtMsg. – LaughingJohn Aug 18 '10 at 12:07