You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将ComboBox文本值设为函数输出?异常问题求助

ComboBox无法直接显示数据库查询函数返回值的异常问题

异常现象

以下代码均能正常设置ComboBox的Text值:

  • 直接赋值字符串:
item.Text = "test";
  • 通过变量赋值:
string testStr = "test";
item.Text = testStr;
  • 用非空字符串拼接函数返回值后赋值:
string testStr = "test" + function();
item.Text = testStr;
string testStr = " " + function();
item.Text = testStr;

但以下代码完全无法生效:

  • 直接赋值函数返回值:
item.Text = function();
  • 用空字符串拼接函数返回值后赋值:
testStr = "" + function();
item.Text = testStr;

需要说明的是,目标函数在其他场景下工作完全正常,能返回合法字符串,现在只需要让item.Text = function();这行代码生效。

目标函数定义

public static string getStringFromDB(string sqlStr)
{
    string result = null;

    SqlConnection conn;
    conn = openCon();

    SqlCommand cmd = new SqlCommand(sqlStr, conn);
    try
    {
        result = (string)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        result = getIntFromDB(sqlStr).ToString();

    }

    closeConn(conn);
    return result;
} 

额外测试结果

执行以下代码时,MessageBox.Show(item.Text)能正常弹出并显示正确内容,但ComboBox的Text区域依然无任何数据展示:

item.Text = getStringFromDB("SELECT " + dbStrings[2] + " FROM " + dbStrings[0] + " WHERE " + dbStrings[1] + " = " + getIntFromDB("SELECT " + item.Name + " FROM MASTER WHERE MASTER_ID = " + recordID + ";"));
MessageBox.Show(item.Text);

后续情况

今早未对代码做任何修改,原本异常的代码突然恢复正常,完全不清楚原因。

内容的提问来源于stack exchange,提问作者K.Ward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:05:20