I have the following code to populate 3 comboboxes:
private void PopulateDDLs()
{
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
DataTable dt;
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand("sql query here", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
ddl1.ValueMember = "col1";
ddl1.DisplayMember = "col2";
ddl1.DataSource = dt;
ddl2.ValueMember = "col1";
ddl2.DisplayMember = "col2";
ddl2.DataSource = dt;
ddl3.ValueMember = "col1";
ddl3.DisplayMember = "col2";
ddl3.DataSource = dt;
}
connection.Close();
}
}
}
However, when I execute this program, and make a selection from one of the comboboxes, the same value automatically gets selected from the other comboboxes. Any idea why this is happening and how to stop it from happening more importantly?
If I create 3 functions, 1 for each combobox, then everything works fine.
This project is a Word Document level project for Word 2010 created using .NET-4.0 using VS2013.
New much improved solution:
A DataSource is more than just the data.
There is hidden default BindingSource that makes the ComboBoxes follow.
To avoid this coupling and also the data replication in the first version of this answer, all you need to do is create a separate BindingSource for each ComboBox. These share the DataTable but have each its own rowPointer:
BindingSource bS1, bS2, bS3;
..
..
..
..
dt = new DataTable();
dt.Load(reader);
bS1 = new BindingSource();
bS1.DataSource = dt;
bS2 = new BindingSource();
bS2.DataSource = dt;
bS3 = new BindingSource();
bS3.DataSource = dt;
..
ddl1.DataSource = bS1 ;
ddl2.DataSource = bS2 ;
ddl3.DataSource = bS3 ;
..
..
Now the ComboBoxes can be changed independently.
Note: My first version worked but was the wrong way do it. Sorry..!
Related
I am recently getting back into coding. I have been working on this Snake Game program that i've been following a tutorial on. However, I am a tad confused as to why its saying "The name dataGridView1 does not exist in the current context. Basically what I am trying to do is display score history in my program through a database and I have followed everything exactly how it is on the tutorial, just cant seem to make it work though. Any help would be appreciated as I am a complete noob at this, thank you!
private void UpdateScoreBoard()
{
//Get data from database and show in data grid view
string query = "SELECT Date,Name,Scores FROM scores";
using(SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
}
}
}
}
You need to declare it in your Form object to be accessible (check the example here):
public class Form1 : System.Windows.Forms.Form
{
// Declare the gridview as a class member.
DataGridView dataGridView1 = new DataGridView();
// Rest of the code
private void UpdateScoreBoard()
{
//Get data from database and show in data grid view
string query = "SELECT Date,Name,Scores FROM scores";
using(SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
}
}
}
Then at some point you need to add it to the form
this.Controls.Add(songsDataGridView);
I have a stored procedure which actually concatenates 2 columns and returns a DataTable.
Its as below:
create procedure [dbo].[spEnqIDFyYear]
as
begin
select CONVERT(nvarchar(50),enq_id)+'/'+CONVERT(nvarchar(50),YEAR(fy_year)) as EnqIDFyYear from Sample.dbo.enquiry_details
end
GO
The output is as follows:
EnqIDFyYear
1/2015
2/2014
I have another procedure, whose output is as below:
profile_name
ProfileA
ProfileB
I bind both the procedures to 2 DataTables, merge those 2 DataTables into a 3rd one and bind the resulting DataTable to the gridview.
But the gridview is not showing as proper. It shows as below:
The rows should be aligned to each other. How to achieve it?
Code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt1 = PopulateDashBoardGrid1();
DataTable dt2 = PopulateDashBoardGrid2();
DataTable dt3 = new DataTable();
dt3 = dt1.Copy();
dt3.Merge(dt2);
GridView1.DataSource = dt3;
GridView1.DataBind();
}
//Populate the main DashBoard Grid
public DataTable PopulateDashBoardGrid1()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spEnqIDFyYear", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
public DataTable PopulateDashBoardGrid2()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spClientProfileName", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
Experts please help.
Regards
Anurag
You are getting that kind of output, because Merge works in that way if the columns are not same of two datatables. So you need to write some custom code.
Here is what I have:-
static DataTable MergeDataTables(DataTable dt1, DataTable dt2)
{
DataTable dt3 = dt1.Copy();
foreach (DataColumn dc in dt2.Columns)
{
dt3.Columns.Add(dc.ColumnName).DataType = dc.DataType;
}
for (int i = 0; i < dt3.Rows.Count; i++)
{
foreach (DataColumn dc in dt2.Columns)
{
string col = dc.ColumnName;
dt3.Rows[i][col] = dt2.Rows[i][col];
}
}
return dt3;
}
You can call this method to merge both datatables.
Here is the code for displaying db table record in data grid view
try
{
Query = "Select Code,Description,Rate,Bottles from Items ";
dba = new SQLiteDataAdapter(Query, GlobalVars.conn);
testDs = new DataSet();
dba.Fill(testDs, "Items");
dtgitems.DataSource = testDs.Tables[0];
dtgitems.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
What it want is when form initially Loads data grid view shouold shows empty row for insertion of new records . How i can accomplish this?Thanks
dba.Fill(testDs, "Items");
dtgitems.AllowUserToAddRows = true;
dtgitems.EditMode = DataGridViewEditMode.EditOnKeystroke;
dtgitems.DataSource = testDs.Tables[0];
i use this code when i want my gridview become empty hope it helps
DataTable dtable = new DataTable();
BindingSource bsource = new BindingSource();
DataSet dset = new DataSet();
dtable.Columns.Add("Delete");
dtable.Columns.Add("FileName");
dtable.Columns.Add("FileVersion");
dtable.Columns.Add("FileSize");
dtable.Columns.Add("InstallFolder");
dtable.Columns.Add("fnameorig");
dset.Tables.Add(dtable);
bsource.DataSource = dset.Tables[0].DefaultView;
Gridview1.DataSource = bsource;
I need to populate grid based on dropdownlist selected value: my c# coding is
protected void atddroplist_SelectedIndexChanged(object sender, EventArgs e)
{
empatdListBI c = new empatdListBI();
DbConnection b = new DbConnection();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
if (atddroplist.SelectedIndex == 1)
{
b.OpenConnection();
dt = c.LoadRecords(empText.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
b.CloseConnection();
}
}
With this coding Iam unable to see Grid in output. Please help me out
We can check few things
- AutoPostBack of dropdown is set to True
- We are getting data in dt
- If necessary we can put grid in the updatepanel on your page
if (atddroplist.SelectedIndex == 1)
{
empatdListBI c = new empatdListBI();
DbConnection b = new DbConnection();
SqlDataAdapter da = new SqlDataAdapter();
DataTable DT = new DataTable();
DT = c.LoadRecords(empText.Text);
b.OpenConnection();
if (DT.Rows.Count == 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "PopUp", "alert(' Record Not Found...');", true);
txtsearchrecord.Text = "";
txtsearchrecord.Focus();
}
else
{
GridView1.DataSource = DT;
GridView1.DataBind();
}
b.CloseConnection();
}
i want to fill a combobox with data from the database when the page load
I had written the code as below
private void QuotationForm_Load(object sender, EventArgs e)
{
MessageBox.Show("hghjgvhg");
comboboxload();
}
public void comboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from jobcodemastertable",oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
oleDbConnection1.Close();
}
it doesnot deturns an error or exception but doesnot load the combobox with data values
try this
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
You may need to bind datatable's view with combo box
cmbjobcode.DataSource = dt.DefaultView;
You're missing the DataBind method
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();
You have to call DataBind method on your combo. Thats why its not populating.