2010-08-18 5 views
2

DataTable에서 값의 인덱스를 가져와야합니다.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]); 

디버깅 값은 동일하지만 항상 -1을 반환 할 때 분석했습니다. 내가 할 수있는 일은 무엇인가?

당신은 행이 데이터 테이블 dtMsg에 실제로 데이터 테이블 (DT)의 행을 찾고 있습니다

답변

6

....

시도 :

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

가 실제로는 항상 어쨌든 당신이로 0을 반환하는 것입니다 인덱스를 기준으로 행을 참조합니다.

dtMsg 행의 값을 기준으로 dt에서 행을 찾으려면 Find() 또는 Select()와 같은 것을 사용해야합니다.

 // 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 테이블의 기본 인덱스 있다고 가정

는 Heres는 몇 가지 예제 코드입니다.

+0

아니요. 두 번째 쿼리에서 첫 번째 쿼리의 모든 메시지를 가져 오지 않습니다. 하나의 메시지가 나타납니다. dt에 모든 메시지가 포함됩니다. 색인을 가져와야하는 행이 하나만있는 dtMsg. dtMsg가 아닌 dt를 찾으려고합니다. –

+1

dtMsg에서 하나의 메시지가 있는데 dt에서 해당 메시지의 해당 색인을 찾아야합니다. 맞습니까? 그렇다면 dtMsg의 행에서 MessageID 값을 사용하여 dt를 찾거나 선택해야합니다. – LaughingJohn

+0

답변을 추가 한 코드를 참조하십시오 .. – LaughingJohn