Nick Proud Nick Proud - 3 months ago 21
C# Question

Connection to SQL Server through ADO.NET - Empty Listbox

Trying to set up a connection to my local SQL Server Express instance so that I can display columns in a listbox. Th build runs fine and I can't see errors, but there is no data in the listbox. I have tested the query and that is fine. I am using NT Authentication to the database. Any ideas where I might have gone wrong?

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
string commstring = "Driver ={SQL Server}; Server = DESKTOP-5T4MHHR\\SQLEXPRESS; Database = AdventureWorks2014; Trusted_Connection = Yes;";
string connstring = "SELECT FirstName, LastName FROM Person.Person";

SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);

DataSet customerDataSet = new DataSet();
customerDataAdapater.Fill(customerDataSet, "Person.Person");

DataTable customerDataTable = new DataTable();
customerDataTable = customerDataSet.Tables[0];

foreach (DataRow dataRow in customerDataTable.Rows)
{
customers.Items.Add(dataRow["FirstName"] + " (" + dataRow["LastName"] + ")");
}
}
}

Answer

I tested your code in a sample project here and I realized you passed the parameters to SqlDataAdapter constructor in a wrong order.

After changing the follow line:

SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);

by

SqlDataAdapter customerDataAdapater = new SqlDataAdapter(connstring, commstring);

the listbox was filled successfully.

Comments