使用Entity Framework,我有一个Combobox,显示从数据库中检索的数据列表。
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);
}
}
}
}
我正在尝试将表单中的数据保存回数据库,尝试转换从Combobox中选择的值时会发生错误。即使我将它转换为正确的类型,它也不会保存所选的值!但是这个,
我对这里的错误一无所知?有人可以告诉我如何纠正这个问题吗?
谢谢。
答案 0 :(得分:1)
newBreakdown.BrkdwnType = breakdownType.ToString();
这里你只是调用你的对象的.ToString()
方法,所以它返回你可以在数据库表记录中查看的类型名称,用于获取BrkDwnType属性值,你应该将语句改为
newBreakdown.BrkdwnType = breakdownType.BrkdwnType;
答案 1 :(得分:0)
它应该只是:
newBreakdown.BrkdwnType = cmbBreakdownType.SelectedItem.ToString();
如果你只想要字符串值,不需要转换selectedItem。从设计的角度来看,您应该规范化您的数据库,并使用一个ID来获取引用具有BreakDown类型的另一个表的breakDownType。