2015-12-28 50 views
0

我有下面的代碼填充用於填充節點的樹狀的數據集:如何擺脫數據集中的單引號?

try 
{ 
    SqlCommand cmd2 = new SqlCommand("SELECT [ACCT_GRP], [ACCT_GRP_PK] FROM [ACCT_GRP_LIST] " + 
    "ORDER BY [ACCT_GRP] ASC", con4); 
    SqlDataAdapter da = new SqlDataAdapter(cmd2); 
    DataSet PrSet = new DataSet(); 

    da.Fill(PrSet, "ACCT_GRP"); 
    TreeViewAccts.Nodes.Clear(); 
    foreach (DataRow dr in PrSet.Tables[0].Rows) 
    { 
     TreeNode tnParent = new TreeNode(); 
     tnParent.Text = dr["ACCT_GRP"].ToString(); 
     tnParent.Value = dr["ACCT_GRP_PK"].ToString(); 
     tnParent.PopulateOnDemand = true; 
     tnParent.SelectAction = TreeNodeSelectAction.SelectExpand; 
     TreeViewAccts.Nodes.Add(tnParent); 
     FillTree_Child(tnParent, tnParent.Text.ToString()); 
    } 
} 
catch (Exception ae) 
{ 
    Response.Write(ae.Message); 
    //ErrorLogging.WriteToEventLog(ae); 
} 

當然,這是怎麼回事的是,如果我的ACCT_GRP名字之一中有一個撇號(即「約翰麪包店「),它會引發錯誤。有誰知道如何解決這一問題?我想我需要一個Replace命令,但我不知道它的正確語法。

+0

你得到什麼錯誤? – wentimo

+1

你是否已經完成了一個關於如何使用'string.Replace'方法的谷歌搜索..你可能想在最後使用它或者你的博士例如 'tnParent.Text = dr [「ACCT_GRP」]。ToString() .Replace(「'」;「''」)'; – MethodMan

回答

3
tnParent.Text = dr["ACCT_GRP"].ToString().Replace("'"; "''"); 
+0

@JohnnyBones,你可以用'string.Replace'做很多很酷的事情,你也可以有多個string.Replace調用內聯以及 – MethodMan

+0

這工作,除了我必須改變替換括號內的分號到一個逗號。謝謝! –

+0

聽起來不錯@JohnnyBones – MethodMan

1

所以,如果你把字符串,你可以做一個像這樣的替換。

string parent = tnParent.Replace("'","''"); 

然後將父字符串放入?

1

可以使用TSQL太取代:

SqlCommand cmd2 = new SqlCommand("SELECT REPLACE([ACCT_GRP], '''', '') as ACCT_GRP, [ACCT_GRP_PK] FROM [ACCT_GRP_LIST] " + "ORDER BY [ACCT_GRP] ASC", con4);