简体   繁体   English

无法在 C# windows 应用程序的数据库中保存组合框选定的索引

[英]Unable to save combobox selected index in database in C# windows application

I am able to bind the data from database to a ComboBox , but while trying to save selected index value back, it shows a null reference error .我能够将数据库中的数据绑定到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;
}

截屏

The reason you are getting a NullReferenceException is because you set the reference to null yourself.您收到NullReferenceException的原因是您自己将引用设置为null The problem lies within your getPartyAccType :问题在于您的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;
}

There is no need to null the dllAccountType whatsoever.没有必要将dllAccountType设为null Nulling this means completely removing the reference to your component, which is not what you want.清空这意味着完全删除对您的组件的引用,这不是您想要的。 Also, you don't need to null the accountPartyType ( ListType in your code) variable, the .NET garbage collector will remove the object from memory if needed;此外,您不需要将accountPartyType (代码中的ListType )变量置null ,如果需要,.NET 垃圾收集器将从内存中删除该对象; there is no need to do this yourself.没有必要自己做这件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM