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

如何在C# WinForms中无需绑定控件编程获取MySQL数据集的订单状态码

解决方案

完全可以实现,你调用ecom_ordersTableAdapter.Fill()方法后,匹配订单号的所有订单数据已经被加载到this.rBTCO_DBDataSet1.ecom_orders数据表中,不需要借助绑定的隐藏文本框中转,直接从数据表读取status字段的值即可。

你只需要把代码中statusCode = statusdata.Text;这一行替换为直接从DataTable取数的逻辑即可,修改后的完整代码如下:

private void getCustData2DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    string ordnum = null;
    string statusCode = null;
    
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = getCustData2DataGridView.Rows[e.RowIndex];
        ordnum = row.Cells[0].Value.ToString();   
    }

    try
    {
        this.ecom_ordersTableAdapter.Fill(this.rBTCO_DBDataSet1.ecom_orders, ordnum);
    }
    catch (System.Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
        return;
    }

    // 直接从填充后的DataTable取status字段值,不需要隐藏文本框
    if (this.rBTCO_DBDataSet1.ecom_orders.Rows.Count > 0)
    {
        statusCode = this.rBTCO_DBDataSet1.ecom_orders.Rows[0]["status"].ToString();
    }

    switch (statusCode)
    {
        case "NS":
            label5.Text = "Processing";
            label5.ForeColor = Color.Green;
            break;
        case "P":
            label5.Text = "Pending Payment";
            label5.ForeColor = Color.Blue;
            break;
        case "X":
            label5.Text = "Cancelled";
            label5.ForeColor = Color.Red;
            break;
        case "C":
            label5.Text = "Completed";
            label5.ForeColor = Color.Blue;
            break;
        default:
            label5.Text = null;
            label5.ForeColor = Color.Black;
            break;
    }
}

改动说明

  • 移除了对隐藏控件statusdata的依赖,直接从查询后的数据表读取状态码
  • 新增了数据行存在性判断,避免查询结果为空时触发空引用异常
  • 修复了原代码中default分支label5.Text = null后缺失分号的语法错误

内容的提问来源于stack exchange,提问作者Dave Skowron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 23:24:03