2011-09-05 30 views
1

我是新的C#..努力學習它..我想知道如何檢索基於數據行中的一列值的整個行數據。我可以提供一個示例清楚..如何從基於一列值的數據行檢索整行數據

MerchantNo TerminalNum CardType Date 
110033445 770010449 Amex 5/09/2011 

現在我想根據商戶數量來檢索此行,然後將其插入到SQL表..

我在想什麼是:

if(MerchantNo!="") 
then retrieve the row 
     and insert data in sql table.. 

其實我我工作的導入Excel的file..Hopeü明白我的問題

string Mno = ""; 
      foreach (DataRow rowExcel in dtExcel.Rows) 
      { 

       foreach (DataColumn colExcel in dtExcel.Columns) 
       { 
        Mno = rowExcel[colExcel].ToString().Trim(); 
        if (Mno != "") 
        { 
         string Mno1 = Mno.Substring(16, 10); 
         Mno =Mno1.ToString(); 
         //Int32 MerchNo = Convert.ToInt32(Mno); 
        } 
        break; 
       } 
       if(Mno!="")// Mno contains the exact MerchantNo. 
       { 


       } 

       //break; 

      } 
+0

您從哪裏獲取的行?一個GridView或DataRow 或其他? – Mentoliptus

+0

對不起,遲到的響應..我想從DataRow檢索行。我有一個數據表充滿了這種數據.. – Nazima

回答

0
//check if MerchantNo column is neither null nor empty 
//r is an object of DataRow 
if (Convert.IsDBNull(r["MerchantNo"]) == false && r["MerchantNo"].ToString().Trim() != String.Empty) 
{ 
     //Build an Sql Insert statement based on the data or row 
     string strSql = String.Format("INSERT INTO SOMETABLE(X,Y,Z) VALUES('{0}', '{1}', '{2}');", r["colName1"], r["colName2"], r["colName3"]); 
} 
0

什麼Waqas說過類似,但增加了foreah循環澄清:

int MerchNo = 0; 
foreach (DataRow r in dtExcel.Rows) 
{ 
    if (!String.IsNullOrEmpty(r["MerchantNo"].ToString().Trim()) && 
     Int32.TryParse(r["MerchantNo"].ToString().Trim(), out MerchNo)) 
    { 
     string strSql = String.Format("INSERT INTO SomeTable(MerchantNo, TerminalNum, CardType, Date) VALUES('{0}', '{1}', '{2}', '{3}');", r["MerchantNo"], r["TerminalNum"], r["CardType"], r["Date"]); 

     SqlCommand scInsertCommand = new SqlCommand(strSql); 

     //do transacion and connection assignment, and error handling 

     scInsertCommand.ExecuteNonQuery(); 
    } 
} 
相關問題