techno techno - 5 months ago 17
SQL Question

DataGridView Not showing Data

I have the following code to display the data in a

DataGridView
from a table. But the
DataGridView
is empty:

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

private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("sdgds");
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
string sql = "SELECT * FROM mytable";
SqlConnection myConnection = new SqlConnection("user id=test;" +
"password=test;server=MOBILE01;" +
"Trusted_Connection=yes;" +
"database=mydatabase; " +
"connection timeout=30");
myConnection.Open();


sCommand = new SqlCommand(sql, myConnection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();

sAdapter.Fill(sDs);


sAdapter.Fill(sDs, "mytable");
dataGridView1.ReadOnly = true;

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
myConnection.Close();
}
}
}

Answer

Because you didn't set your DataGridView.DataSource property:

dataGridView1.DataSource = sDs.Tables["mytable"];
Comments