2013-02-01 55 views
0

我試圖在數據庫中插入checkboxlist多個值,插入值在不同的表中的行

這裏是我的插入代碼:

string str = string.Empty; 
    try 
    { 
     var sb = new StringBuilder(); 

     var collection = ListLawCat.CheckedItems; 
     foreach (var item in collection) 
     { 
      str += item.Value + ","; 
     } 

     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = connString; 

     SqlCommand com = new SqlCommand(); 
     com.Connection = con; 
     com.CommandText = "Insert into TABLE (COL1, COL2) values ('" + str + "','" + DocID + "') "; 
     com.CommandType = CommandType.Text; 

     con.Open(); 

     int j = com.ExecuteNonQuery(); 

     if (j > 0) 
     { 
      Response.Write("insert successfully"); 
      Response.Write(str); 
     } 
     else 
     { 
      Response.Write("Not Inserted"); 
     } 
     con.Close(); 
    } 
    catch (Exception ex) 
    { 
     Response.Write(ex.Message); 
    } 

但是這個代碼將全部checkboxlist值存儲在一排。

這是一種將值存儲在單獨表格行中的方法嗎?

回答

2

試試這個

string str = string.Empty; 
try 
{ 
    var sb = new StringBuilder(); 
    SqlConnection con = new SqlConnection(); 
    con.ConnectionString = connString; 

    SqlCommand com = new SqlCommand(); 
    com.Connection = con; 
    var collection = ListLawCat.CheckedItems; 
    foreach (var item in collection) 
    { 

    com.CommandText = "Insert into TABLE (COL1, COL2) values ('" + item.Value+ "','" + DocID + "') "; 
    com.CommandType = CommandType.Text; 

    con.Open(); 

    int j = com.ExecuteNonQuery(); 
    if (j > 0) 
    { 
     Response.Write("insert successfully"); 
     Response.Write(item.Value); 
    } 
    else 
    { 
     Response.Write("Not Inserted"); 
    } 
    con.Close(); 
    } 
} 
catch (Exception ex) 
{ 
    Response.Write(ex.Message); 
} 
相關問題