I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}
Related
I have created a Combo box bound to "Clinics" field of a table. I wanted to show "All" on the first line of the Combo box list to show all activities of the clinics by default in a table. When a specific clinic is selected it shows the activities of the selected clinic.
My script looks like this:
[My Code looks like this]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
comboBox1.DisplayMember = "clinic";
comboBox1.DataSource = dt;
sqlconn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ] where clinic='"+comboBox1.Text.ToString()+"'";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
dataGridView1.DataSource = dt;
sqlconn.Close();
}
}
}
First off, refrain from SELECT *, instead select only needed columns.
You can add All using a UNION.
In this example, table name is Categories with the intent to provide the primary key for use after a selection is made and description to display.
SELECT CategoryID, CategoryName FROM dbo.Categories;
Now using a SELECT with 0 in this case to represent an identifier and 'All` to display in the ComboBox then union for all rows in the table.
SELECT 0 AS CategoryID, 'All' AS CategoryName
UNION ALL SELECT CategoryID, CategoryName FROM dbo.Categories;
In code you can read the data into a DataTable, set DisplayMember, in this case to CategoryName and ValueMember to CategoryID.
When a selection is made check SelectedItem, if 0 All is the selection, else an existing primary key would be used for your business logic.
in SQL Server I have a table that have id,office, transpo and allowance columns. Now my code goes like this.
using (SqlConnection conn = new SqlConnection("Data Source=PC; Initial Catalog=DATABASE; Integrated Security=True"))
{
conn.Open();
SqlCommand sc = new SqlCommand("select * from branch order by office asc", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("OFFICE", typeof(string));
dt.Load(reader);
comboboxDestination.ValueMember = "ID";
comboboxDestination.DisplayMember = "OFFICE";
comboboxDestination.DataSource = dt;
conn.Close();
}
Now it displays ok, I can transfer what's in the combobox to the other form like I use to do.
string destination;
destination = comboboxDestination.Text.ToString();
My question is, in my table, I also have transpo and allowance column. How can I transfer the appropriate value of that in a variable whenever what is picked in the displayed combobox which is the office column?
To get values corresponding to combo box selection please go through below code:
1.Make data table accessible outside the function so define it with global aspect.
DataTable dt = new DataTable();
Fill data table using your function.
using (SqlConnection conn = new SqlConnection("Data Source=PC; Initial Catalog=DATABASE; Integrated Security=True"))
{
conn.Open();
SqlCommand sc = new SqlCommand("select * from branch order by office asc", conn);
SqlDataReader reader = sc.ExecuteReader();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("OFFICE", typeof(string));
dt.Load(reader);
comboboxDestination.ValueMember = "ID";
comboboxDestination.DisplayMember = "OFFICE";
comboboxDestination.DataSource = dt;
conn.Close();
}
Getting combo box value on button click or combo box selection change
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string destination="";
string transpo="";
string allowance="";
destination = comboboxDestination.Text.ToString();
//Function to get values regarding selected combo box value.
foreach(DataRow row in dt.Rows)
{
if(row["OFFICE"].ToString().ToUpper() == destination.ToUpper())
{
transpo=row["Transpo"].ToString();
allowance=row["Allowance"].ToString();
break;
}
}
Console.Write("Transpo = "+ transpo);
Console.Write("Allowance= "+ allowance);
}
Lets say I have a table named Table_T in the SQL database and it contains 6 columns (column1, column2, ..., column6).
The following code populates all columns from the database into dataGridView:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(
"Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("SELECT *FROM Table_T");
cm.Connection = cn;
SqlDataAdapter da = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
dataGridView1.DataSource = dt;
}
But how can I only select column3 & column5 and populate them into dataGridview1?
SELECT column3, column5 FROM Table_T
Why wouldn't that work?
if you dont need everything back from the table you should use
select col1, col2 from table
and if you need conditions on it use your where clause
However if do need to grab all th data but display only certain information at certain times I would use a foreach loop like so
foreach(var item in dt.Rows)
{
var colValue0 = item[0].ToString()
var colValue1 = item[1].ToString()
var colValue2 = Convert.ToIn16(item[2])
}
---- edit ----
relooking at your question, if you were binding this to a gridview and only wanted certain information you should add these values to a new datatable then display only the new datatable
so you would need to do something like
var bindableDt = new Datatable();
bindableDt.Columns.Add("colName1")
bindableDt.Columns.Add("colName2")
foreach(var item in dt.Rows)
{
bindableDt.Row.Add(dt.Rows[0], dt.Rows[1]);
}
gridview.Datasource = bindableDt;
[This answer was initially posted as comment by #capricorn]
SqlCommand cm = new SqlCommand("SELECT column3,column5 FROM Table_T")
this code worked very well. thank you all for your help . all respect and regards.
I am trying to display my mysql database table on a DataGridView using c# . but nothings happening . please tell me where i've gone wrong in my code
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("Server = localhost; Database=project; user=root;password=''");
conn.Open();
string query = "SELECT * FROM billing";
MySqlDataAdapter bills = new MySqlDataAdapter(query, conn);
MySqlCommandBuilder cbuilder = new MySqlCommandBuilder(bills);
DataTable dtable = new DataTable();
bills.Fill(dtable);
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dtable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
bills.Update(dtable);
}
Here I am getting the values to my grid. This is Connection of my database table. It is okay and working well but i want to show my Qty field data by dividing my txtOrderQuantity (textbox id name)value.
<asp:TextBox ID="txtOrderQuantity" runat="server"
ontextchanged="txtOrderQuantity_TextChanged" AutoPostBack="true"> </asp:TextBox>
How i can show my grid view field by dividing by 2 with txtorderQuantity.
public DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],[Qty],[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}
you can do it two ways.
1) you can send the value of the text field to your GetData() method. and then prepare your select statement in the following way
public DataTable GetData(int OrderQuantity)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],([Qty]/OrderQuantity )as Qty,[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}
2) you can use RowDataBound Event of GridView. it occurs when a single DataRow have bound in the gridView.
void YourGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
// I assume the index of Qty column is 4
e.Row.Cells[4].Text = decimal.Parse(e.Row.Cells[4].Text)/decimal.Parse(txtOrderQuantity.Text) ;
}
}
Use RowDataBound event of gridview and perform following steps:
Find the textbox control and its value.
Find the MyQty value and divide it with textbox value(use specific type cast wherever needed.)
Find your control to display MyQty valud and assign calculated value.