我在分配值时遇到问题。
string userlanguages = string.Empty;
try
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
userlanguages = myDS.Tables[0].Rows[0]["[s_langName]"].ToString();
}
catch (SqlException exc)
{
Response.Write(exc.Message);
}
finally
{
objcon.Close();
Class1.langKnwn = userlanguages;
}
}
假设,这里的myDs包含三个值。然后我将如何将它们分配给单个字符串(在本例中为“userlanguages”)。我在另一个页面中使用Class1.langKnwn来显示用户选择的语言(在许多情况下可能超过1种语言)。
请帮帮我。
答案 0 :(得分:2)
像
这样的东西List<string> languages = new List<string>();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
languages.Add(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
userlanguages = String.Join(",", languages);
答案 1 :(得分:1)
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
for(int ndx=0;ndx<myDS.Tables[0].Rows.Count;ndx+=1)
{
if(ndx==0)
{
userlanguages = myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
else
{
userlanguages = userlanguages+","+ myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
}
答案 2 :(得分:0)
如果我正确理解您的问题,在您的情况下使用SqlDataReader
可能是更好的选择。
using (SqlConnection objcon= new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] = @id", objcon);
cmd.Parameters.AddWithValue("@id", Class1.EmployeeId);
connection.Open();
SqlDataReader reader = cmd .ExecuteReader();
string userlanguages = string.Empty;
while (reader.Read())
{
string str = reader.GetString(0);
userlanguages = String.Join(",", userlanguages);
}
reader.Close();
}
你应该总是使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
答案 3 :(得分:0)
试试这个
使用using System.Text;
namesapce
然后在您的块中编写该代码
StringBuilder sb = new StringBuilder();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
{
sb.Append(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
sb.Append(",");
}
//在最后获取字符串
string myString = sb.ToString();
myString= myString.Substring(0, myString.Length - 1);
答案 4 :(得分:0)
userlanguages = string.Join(",", myDS.Tables[0].AsEnumerable()
.Select(row => row.Field<string>("[s_langName]"))
.ToArray());