Getting index of a value in DataTable

后端 未结 1 1708
闹比i
闹比i 2021-01-15 11:25

i need to get index of a value in DataTable.

I\'m trying to get like that.

 SqlDataAdapter da = new SqlDataAdapter(\"SELECT MessageID,SenderID,Messag         


        
相关标签:
1条回答
  • 2021-01-15 12:02

    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.

    0 讨论(0)
提交回复
热议问题