1

使用实体框架,我有一个组合框,显示从数据库中检索到的数据列表。

using System;  //I removed the other using statements here to preserve space

namespace ExTea_BackEnd
{
    public partial class frmAddBreakdown : Form
    {
        ExTeaEntities Breakdowns;
        Breakdown_Type BreakdownTypes;

        public frmAddBreakdown()
        {
            InitializeComponent();
        }

        private void cmbBreakdownType_SelectedIndexChanged(object sender, EventArgs e)
        {
            Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
            string selectedBreakdownTypeId = breakdownType.BrkdwnId;

            IQueryable<Breakdown_Type> breakdownTypeQuery = from t in Breakdowns.Breakdown_Types
                                                            where t.BrkdwnId == selectedBreakdownTypeId
                                                            select t;
            List<Breakdown_Type> selectedBreakdownId = breakdownTypeQuery.ToList();

            if (selectedBreakdownId != null && selectedBreakdownId.Count > 0)
            {
                BreakdownTypes = selectedBreakdownId.First();
                txtBreakdownId.Text = BreakdownTypes.BrkdwnId.ToString();
            }
            else
            {
                BreakdownTypes = null;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Breakdown newBreakdown = new Breakdown();

                Breakdown_Type breakdownType = (Breakdown_Type)cmbBreakdownType.SelectedItem;
                newBreakdown.BrkdwnType = breakdownType.ToString();   //this is where the error occurs

                newBreakdown.MachineId = txtMachineId.Text.Trim();
                newBreakdown.MachineType = txtMachineType.Text.Trim();
                newBreakdown.ReportedDate = dtpDate.Value;
                newBreakdown.JobStatus = "I";

                Breakdowns.AddToBreakdowns(newBreakdown);
                int rowsAffected = Breakdowns.SaveChanges();
                if (rowsAffected > 0)
                {
                    MessageBox.Show(rowsAffected + " records added!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured! " + ex.Message);
            }
        }
    }
}

我正在尝试将表单中的数据保存回数据库,尝试转换从组合框中选择的值时发生错误。即使我已将其转换为正确的类型,它也不会保存所选值!但是这个,

在此处输入图像描述

我对我在这里做错了什么一无所知?谁能告诉我如何纠正这个问题?

谢谢你。

4

2 回答 2

1
newBreakdown.BrkdwnType = breakdownType.ToString();

在这里,您只是调用.ToString()对象的方法,因此它返回您可以在数据库表记录中查看的类型名称,以获取 BrkDwnType 属性值,您应该将语句更改为

newBreakdown.BrkdwnType = breakdownType.BrkdwnType; 
于 2012-10-20T09:19:01.297 回答
0

它应该是:

            newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString(); 

如果您只想要字符串值,则无需转换 selectedItem 。从设计的角度来看,您可能应该规范化您的数据库并为 breakDownType 使用一个 ID,该 ID 引用另一个具有 BreakDown 类型的表。

于 2012-10-20T09:30:09.113 回答