[英]Unable to save combobox selected index in database in C# windows application
我能够将数据库中的数据绑定到ComboBox
,但是在尝试将选定的索引值保存回来时,它显示了一个null reference error
。
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
BindPAId();
getPartyAccType();
}
private void btnAdd_Click(object sender, EventArgs e)
{
mode = "New";
// getting error here
string AccTypeIndex = ddlAccountType.SelectedIndex.ToString();
}
public void getPartyAccType()
{
// ddlAccountType.Items.Clear();
PartyAccount objType = new PartyAccount();
List<PartyAccount> ListType = objType.getAccountPartyType();
ddlAccountType.DataSource = ListType;
ddlAccountType.ValueMember = "AccTypeId";
ddlAccountType.DisplayMember = "AccType";
ddlAccountType = null;
ListType = null;
}
您收到NullReferenceException
的原因是您自己将引用设置为null
。 问题在于您的getPartyAccType
:
public void getPartyAccType()
{
PartyAccount account = new PartyAccount();
List<PartyAccount> accountPartyType = account.getAccountPartyType();
ddlAccountType.DataSource = accountPartyType;
ddlAccountType.ValueMember = "AccTypeId";
ddlAccountType.DisplayMember = "AccType";
//ddlAccountType = null;
//accountPartyType = null;
}
没有必要将dllAccountType
设为null
。 清空这意味着完全删除对您的组件的引用,这不是您想要的。 此外,您不需要将accountPartyType
(代码中的ListType
)变量置null
,如果需要,.NET 垃圾收集器将从内存中删除该对象; 没有必要自己做这件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.