当传入参数的值来自Function时,不会返回任何记录
本文关键字:返回 记录 任何 Function 参数 | 更新日期: 2023-09-27 18:22:20
我是一个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中将不会绑定任何记录。
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));
}
}
在数据绑定到Gridview时使用该功能怎么样?
<asp:TextBox ID="Name" runat="server" Text='RemoveExtraSpaces(<%# Bind("Name") %>);' AutoPostBack="false"></asp:TextBox>