Using C in visual studio I am trying to fill a datagridview
Using C# in visual studio.
I am trying to fill a datagridview with a sqlite database. I am not able to get the dataabse to show within the datagridview. Here is the code I have so far..
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SQLite;
namespace SQL_Population_Database
{
public partial class Form1 : Form
{
//Use the following for testing within Visual Studio
private const string dbPOPULATION = \"Data Source = ../../population.db; Version = 3\";
//Use the following for deployment.
//private const string dbPOPULATION = \"Data Source = population.db; Version = 3\";
SQLiteConnection connection = new SQLiteConnection(dbPOPULATION);
SQLiteDataAdapter dataAdapter;
SQLiteCommand command;
DataSet ds = new DataSet();
String sql;
public Form1()
{
InitializeComponent();
}
private void DisplayTable()
{
connection.Open();
DataSet dataSet = new DataSet();
sql = \"SELECT * FROM POPULATION ORDER BY CITIES;\";
dataAdapter = new SQLiteDataAdapter(sql, connection);
dataAdapter.Fill(dataSet);
connection.Close();
dgvEmployees.DataSource = dataSet.Tables[0].DefaultView;
dgvEmployees.ClearSelection();
}
private void Form1_Load(object sender, EventArgs e)
{
DisplayTable();
}
private void RadioButtonChanged(object sender, EventArgs e)
{
if (rdoAdd.Checked)
{
txtCity.Enabled = true;
txtPopulation.Enabled = true;
}
else if (rdoDelete.Checked)
{
txtCity.Enabled = true;
txtPopulation.Enabled = false;
}
else if (rdoEdit.Checked)
{
txtCity.Enabled = true;
txtPopulation.Enabled = true;
}
else if (rdoFindByName.Checked)
{
txtCity.Enabled = true;
txtPopulation.Enabled = false;
}
}
}
}
Solution
//Example code for getting database to show within the datagridview
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();//declaring component function
BindGrid();//declaring bind grid function
}
private void BindGrid()//defining bind grid function
{
string constring = @\"Data Source=.\\SQL2005;Initial Catalog=Northwind;User id =
sa;password=pass@123\";//intialise database to costring variable
using (SqlConnection con = new SqlConnection(constring))//setting connection
{
using (SqlCommand cmd = new SqlCommand(\"SELECT * FROM Customers\", con))//geeting data from table
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
}


