AZEEM AHMED AZEEM AHMED - 4 months ago 16
C# Question

Show records in ComboBox on different lines

I want to show all my records in a ComboBox but the records are shown on one line. Here is my code. I made 2 classes from which the data are retrieved.

Data Handler Code:

public DataSet DataLoader(string _strQuery)
{
DataSet ds = new DataSet();
ds.Clear();

using (conn = new SqlConnection())
{
conn = Connection.getconnection();
oda = new SqlDataAdapter(_strQuery, conn);
oda.Fill(ds, "Temp");
conn.Close();
conn.Dispose();
oda.Dispose();
}

return ds;
}


Data Class Code:

public System.String Loadbranch()
{
string BranchName = "";
string strquery = "select * from Expense";
DataHandler dh = new DataHandler();
System.Data.DataSet dsLoadData = new System.Data.DataSet();
dsLoadData = dh.DataLoader(strquery);

if (dsLoadData.Tables["Temp"].Rows.Count > 0)
{
for (int i = 0; i < dsLoadData.Tables["Temp"].Rows.Count; i++)
{
BranchName += dsLoadData.Tables["Temp"].Rows[i]["ExpenseID"].ToString();
}
}

return BranchName;
}


Main Form Where Data Show:

private void Edit_User_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
this.MinimumSize = this.Size;
this.MaximumSize = this.Size;

cbsaveuserid.Items.Add(d.Loadbranch());
}


Please help me to show all records in the ComboBox but on different lines.

Answer

Items represents a collection of objects.

Modify your LoadBranch() method to return a collection of strings (e.g., List<string>), as opposed to one concatenated string.

Modify Edit_User_Load() to loop through the collection and add each element to the cvsaveuserid.Items collection.

I don't have your code, so I can't compile it, but I think this would work:

    public List<string> Loadbranches()
    {
        List<string> branchNames = new List<string>();
        string strquery = "select * from Expense";
        DataHandler dh = new DataHandler();
        System.Data.DataSet dsLoadData = new System.Data.DataSet();
        dsLoadData = dh.DataLoader(strquery);

        if (dsLoadData.Tables["Temp"].Rows.Count > 0)
        {
            for (int i = 0; i < dsLoadData.Tables["Temp"].Rows.Count; i++)
            {
                branchNames.Add(dsLoadData.Tables["Temp"].Rows[i]["ExpenseID"].ToString());
            }
        }

        return branchNames;
    }

    private void Edit_User_Load(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Maximized;
        this.MinimumSize = this.Size;
        this.MaximumSize = this.Size;

        foreach (string branchName in d.Loadbranches())
        {
            cbsaveuserid.Items.Add(branchName);
        }
    }