簡體   English   中英

無法在 C# windows 應用程序的數據庫中保存組合框選定的索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM