简体   繁体   中英

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 .

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. The problem lies within your 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. 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; there is no need to do this yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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