gpt4 book ai didi

c# - 当传入参数的值来自 Function 时,没有记录返回

转载 作者:太空宇宙 更新时间:2023-11-03 16:35:55 25 4
gpt4 key购买 nike

我是一个 VB 人,正在慢慢迁移到 C#。在继续讨论主要问题之前,我想先向您展示我在处理字符串时使用的函数。

class NewString
{
public static string RemoveExtraSpaces(string xString)
{
string iTemp = string.Empty;
xString = xString.Trim();
string[] words = xString.Split(' ');
foreach (string xWor in words)
{
string xxWor = xWor.Trim();
if (xxWor.Length > 0)
{
iTemp += " " + xxWor;
}

}
return iTemp;
}
}

该函数只是删除字符串中的所有尾随空格和多余空格。例如:

NewString.RemoveExtraSpaces("  Stack    OverFlow  ")
==> will return "Stack OverFlow"

所以我的问题是,当我使用该函数删除传入参数的字符串中的空格时,datagridview 中将没有绑定(bind)的记录。

    private void LoadCandidateList(bool SearchAll, string iKey)
{
using (MySqlConnection xConn = new MySqlConnection(ConnectionClass.ConnectionString))
{
using (MySqlCommand xCOmm = new MySqlCommand())
{
xCOmm.Connection = xConn;
xCOmm.CommandType = CommandType.StoredProcedure;
xCOmm.CommandText = "LoadCandidateList";
xCOmm.Parameters.AddWithValue("LoadAll", Convert.ToInt16(SearchAll));

string fnlKey = iKey.Trim();
// when i use the code above, the procedure performs normally
// but if i use the code below, no records will be return
// why is that? i prompt it in the MessageBox to check
// and displays the correct value.

// string fnlKey = NewString.RemoveExtraSpaces(iKey.Trim());
// MessageBox.Show(fnlKey); // => return correct value

xCOmm.Parameters.AddWithValue("iKey", fnlKey);
xCOmm.Parameters.AddWithValue("iCurrentID", _CurrentEventID);

using (DataSet ds = new DataSet())
{
using (MySqlDataAdapter xAdapter = new MySqlDataAdapter(xCOmm))
{
try
{
xConn.Open();
xAdapter.Fill(ds,"CandidateList");
grdResult.DataSource = ds.Tables["CandidateList"];
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "Function Error <LoadCandidateList>", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
xConn.Close();
}
}
}
}
}
}

最佳答案

用单个空格替换空格序列的函数可以在一行中重写:

string.Join(" ", xString.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

如果你想让它成为一个扩展方法,你可以这样做:

static class StringExtensions {
public static string RemoveExtraSpaces(this string xString) {
return string.Join(" ", xString.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries));
}
}

关于c# - 当传入参数的值来自 Function 时,没有记录返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9113086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com