I have used DataRow which could be displayed in a combobox in my WinForm but somehow, it is not working, although the entire table is successfully being displayed in the gridview.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from StuDet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dr[0]);
}
}
You create an empty new row
DataRow dr = dt.NewRow();
and add it Rows.Count times to comboBox1. I think what you want is to go through each row in dt.Rows:
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Roll"]);
}
Just now figured out the answer, Please take a look at the loop at the bottom.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from studet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
////////////////////////////////////////////////////
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
dr[0] = dt.Rows[i][0];
comboBox1.Items.Add(dr[0]);
}
}
Related
I want to use two DataGridViews in this form, which will receive their information from two different tables in one database. But when I run the program, both DataGridViews only display the second table information.
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
dataGridView1.Columns[3].Visible = false;
}
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView2.DataSource = dt;
dataGridView2.DataBind();
}
}
Try this
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
dt = new DataTable();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
You seem to be reusing da and dt. Reusing da is no problem, but reusing dt is. When you assign dt to DataGridView.DataSource, the data is NOT copied! So in the end, both DataGridViews will be using the same DataTable object, that holds the data from the second table (medal).
You could try this:
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
DataTable dt1 = new DataTable();
da.Fill(dt1);
dataGridView1.DataSource = dt1;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
DataTable dt2 = new DataTable();
da.Fill(dt2);
dataGridView2.DataSource = dt2;
}
Edit: renamed the local DataTable variables for clarity.
I have a GridView. I am trying to display DB table data into grid using DataTable. So I am saving the query result in DataTable, but the data is not displayed. Here is my code. Please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dataTable = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString;
string query = "select * from GridExcel";
SqlConnection con1 = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con1);
con1.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your
datatable
da.Fill(dataTable);
Gridview1.DataSource = dataTable;
Gridview1.DataBind();
ViewState["CurrentTable"] = dataTable;
con1.Close();
}
}
Try to use a DataReader:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dataTable = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString;
string query = "select * from GridExcel";
SqlConnection con1 = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con1);
con1.Open();
// create data adapter
SqlDataReader reader = cmd.ExecuteReader();
// this will query your database and return the result to your datatable
dataTable.Load(reader);
Gridview1.DataSource = dataTable;
Gridview1.DataBind();
ViewState["CurrentTable"] = dataTable;
con1.Close();
}
}
The below code is works for me.
string constring = #"Data Source=.\SQL2005;Initial Catalog=gridconnection;";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("select * from GridExcel", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
So here's whats happening. when I press the event button1 to retrieve the data from my database it shows System.Data.DataRowView. But when I press the button1 event again it shows the actual result and correct data. I want to know how to fix this in just one click of a button to display actual data
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"SQLCONNECTIONSTRING");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_members", con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
DataSet ds = new DataSet();
adapter.Fill(ds);
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.Enabled = true;
checkedListBox1.Refresh();
con.Close();
}
try this.. You don't need to execute the query for twice.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"SQLCONNECTIONSTRING");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_members", con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
//SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("FullName", typeof(string));
DataSet ds = new DataSet();
adapter.Fill(ds);
dt=ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.Enabled = true;
checkedListBox1.Refresh();
con.Close();
}
Shouldn't the order of assignment be different?
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
instead of
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.DataSource = ds.Tables[0];
How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}
I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}
you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.