How to display all Database data in Grid View using Data Table? - c#

I have 5 data in my datatbase, these data I want to display in a gridView using Data Table. But my code displays only the last binded data in GridView? My code is. Please point out the mistake?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand("select Date from MusterRoll where EmpCode='"+code+"' and Month='1' and Year='2015'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
string date1 = Convert.ToString(row["Date"]);
DateTime date2 = Convert.ToDateTime(date1);
SqlCommand cmd1 = new SqlCommand(" select TOP 1 m.EmpCode,m.NOH,m.OT,m.Late,m.Early,convert(varchar(10),m.Date,103)AS DATE,convert(varchar(10),s1.Shiftname,103)AS Shift From ShiftChange s,ShiftType s1,MusterRoll m WHERE s1.ShiftID=s.NShiftID and '" + date2 + "'>=Fromdate and Todate>='" + date2 + "' and m.Month = '1' and m.date='"+date2+"' and m.EmpCode='Neena' order by Todate desc", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
//var rows1 = ds.Tables[0].Rows;
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow rpw = dt.Rows[rowIndex];
string EmpCode = rpw.Field<string>("EmpCode");
string NOH = rpw.Field<string>("NOH");
string OT = rpw.Field<string>("OT");
string Latae = rpw.Field<string>("Late");
string Early = rpw.Field<string>("Early");
string date3 =rpw.Field<string>("Date");
string Shift = rpw.Field<string>("Shift");
gvSingleemp.Visible = true;
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
}
}
In my shiftChange table there is no Field for date instead of that I have fromDate and ToDate.I want display employee shifft according to MusterRoll table date. So that first I selected MusteRoll date nd checkrd this date exist in between ShiftChange FromDate and ToDate if exist show the Shift

You are databinding the GridView in a loop. You don't need the loop, just bind it to the DataTable:
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
I still think that you don't need those loops at all. I guess that you want to select all records from EmpDetails where the EmpCode = code and MusterRoll.Month='1' and MusterRoll.Year='2015'. Then you only need one sql query to fill one DataTable which can be used as DataSource for gvSingleemp. Is that correct?
If so, this should work (note that i use the using statement and sql-parameters):
DataTable tblData = new DataTable();
string sql = #"SELECT ed.EmpCode,ed.Name,ed.Age,ed.Date
FROM MusterRoll mr
INNER JOIN EmpDetails ed
ON mr.Date = ed.Date
WHERE mr.EmpCode=#EmpCode AND mr.Month=1 AND mr.Year=2015";
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using(var sda = new SqlDataAdapter(sql, conn))
{
var codeParam = new SqlParameter("#EmpCode", SqlDbType.VarChar).Value = code; // change type accordingly
sda.SelectCommand.Parameters.Add(codeParam);
sda.Fill(tblData); // no need for conn.Open/Close with SqlDataAdapter.Fill
}
gvSingleemp.Visible = true;
gvSingleemp.DataSource = tblData;
If you don't want to join the tables you can also use EXISTS:
string sql = #"SELECT ed.EmpCode, ed.Name, ed.Age, ed.Date
FROM EmpDetails ed
WHERE EXISTS
(
SELECT 1 FROM MusterRoll mr
WHERE mr.EmpCode = #EmpCode
AND mr.Month = 1 AND mr.Year=2015
AND mr.Date = ed.Date
)";

You dont have to use loop to bind the DT to GridView :
SqlCommand cmd1 = new SqlCommand(" select EmpCode,Name,Date,Age from EmpDetails where CompanyID='1'", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource =dt;
gvSingleemp.DataBind();

SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
Da.Fill(data);
gvSingleemp.DataSource = data;
gvSingleemp.DataBind();

Related

da=Fill(ds); error near '=' in asp.net

This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.

c# selecting all record with specific data on datatable

I'm planning to select all rows in my datatable that has 'Dog' in column 2 without using keyword "WHERE" on my query. My guess is to try using DataRow and foreach but I'm not sure where to start. I filled my datatable with records coming from my database and this is what I've done so far.
using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1",con);
DataTable dt = new DataTable();
adp.Fill(dt);
adp.Dispose();
}
This is what my datatable looks like:
Column1 Column2 Column3
1 Dog Labrador
2 Dog Chowchow
3 Cat Persian
4 Cat Stubby
5 Dog German Shepherd
You can filter records when populating table using data adapter by modifying select query:
SELECT * FROM table1 WHERE Column2='Dog'
and second approach if you need to filter later then use this approach - Creating a DataTable From a Query (LINQ to DataSet):
List<DataRow> result = dt.AsEnumerable().Where(row=> row.Field<string>("Column2") = "Dog").ToList();
You can filter records by using DataView and use the RowFilter Property as below:
// Create a DataView
DataView dv = new DataView(dt);
// Filter by an expression.
dv.RowFilter = "Column2 = 'Dog'";
DataTable newTable = view.ToTable();
References:
Creating a DataTable from a DataView
You are looking for a SQL WHERE clause. Always use SqlParameter or similar to insert variables into a query (prevents potential SQL injection attacks if parameter value is user provided).
string genusInput = "Dog"; // might be provided by user input later on
DataTable result = new DataTable();
using (MySqlConnection con = new MySqlConnection(constring)) {
const string query = "SELECT * FROM table1 WHERE Column2 = #genus";
var adp = new MySqlDataAdapter(query, con);
adp.SelectCommand.Parameters.AddWithValue("#genus", genusInput);
adp.Fill(result);
adp.Dispose();
}
Use where to distinguish:
using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1,con);
DataTable dt = new DataTable();
adp.Fill(dt);
IEnumerable<DataRow> query = adp.Where(x => x.Column2 == 'dog').ToList();
DataTable filteredRows = query.CopyToDataTable<DataRow>();
adp.Dispose();
}
using(MySqlConnection con = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1",con);
DataTable dt = new DataTable();
adp.Fill(dt);
adp.Dispose();
DataRow[] dr=dt.select(“Column2=‘Dog’”);
}
https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx
Create where statement in your query as below sample
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * FROM table1 WHERE Column2='Dog'",con);

Error displaying data from DB to predefined columns of datagrid View on button click event

I am using the following code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);
BindingSource bindsrc = new BindingSource();
DataGridView datagridv = new DataGridView();
bindsrc.DataSource = dt;
datagridv.DataSource = bindsrc;
connection.Close();
I have three predefined columns in datagridview1 say 'PLU_Code', 'Barcode' and 'Product_Name'.
I want to display the result (more than one row) of the select query in the datagridview. But I am not getting any.
How do I achieve this?
Try this code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
I got the result. I achieved two empty rows on using #user4340666 code. when i scrolled the grid i found the set of data's been added as new columns leaving predefined column cells empty. so i just cleared the columns.
dataGridView1.Columns.Clear();
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
Try this code:
string getinputs = "Select Query";
connection.Open();
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(getinputs,connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmdbuilder);
DataTable dt = new DataTable();
adapter.Fill(dt);
DataGridView datagridv = new DataGridView();
datagridv.DataSource = dt;
datagridv.DataBind();
connection.Close();

datagridviewcombobox columns Dependent on another column

How To Do This Work on gridviewcomboboxcolumns any idea plx
//Form Load Event
string query="select article_name from article";
SqlCommmand cmd = new SqlCommand(query,con);
SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
combobox1.items.clear();
for(int i=0;i<dt.rows.count;i++)
{
combobox1.items.add(dt.rows[i].cells[0].toString());
}
\ComboBox1 Selected IndexChange Event
string query1="select description from article where article_name='"+combobox1.selectedItem.ToString()+"'";
SqlCommmand cmd1 = new SqlCommand(query1,con);
SqlDataAdapter da1= new SqlDataAdapter(cmd);
DataTable dt1=new DataTable();
da1.Fill(dt1);
combobox2.items.clear();
for(int i=0;i<dt1.rows.count;i++)
{
combobox2.items.add(dt1.rows[i].cells[0].toString());
}
\Now Assume these 2 combox is gridviewCombobox Columns so how to make
this work on gridviewcombobox columns
Project in Windows Form in C#
I m posting this answer after a few months because its helps for
thoose whoose facing problem on DataGridviewComboboxcell
I did my own skill First Fill my first/Main Column
SqlCommand objCmd = new SqlCommand("select distinct article_name from Setup_article_custominvoice", con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
article.DataSource = dt;
//this column1 will display as text
article.DisplayMember = "article_name";
After that i was going on Cell End Edit
if (dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells["article_name"])
{
string CategoryValue = "";
//string CategoryValue1 = "";
if (dataGridView1.CurrentCell.Value != null)
{
CategoryValue = dataGridView1.CurrentCell.Value.ToString();
//CategoryValue1 = dataGridView1.CurrentCell.Value.ToString();
}
//SqlConnection objCon = new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=dbTest3;Integrated Security=True");
string query = "select article_name,composition from Setup_article_custominvoice where article_name='" + CategoryValue + "'";
SqlCommand objCmd = new SqlCommand(query, con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
DataGridViewComboBoxCell t = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2] as DataGridViewComboBoxCell;
t.DataSource = dt;
t.DisplayMember = "composition";
}

Loop through ado.net sql select to add more rows to datatable

I currently have a working query for the first element in the array of ID's as seen below. What I need to do is add a for loop so I rerun the query for every element in the array and add each new row to the datatable but I am not sure how I do this? Unless there is a way I can include all ID's of my array in the where clause so I retrieve all rows through first run.
PID[] is a string array and could have anywhere from 1 to 5 elements that are random ID's.
Any help would be appreciated!
for loop here?
string firstQuery = "select * from Property p " +
"where p.id in (#pID)";
connString.Open();
SqlCommand selectAll = new SqlCommand(firstQuery, connString);
selectAll.Parameters.AddWithValue("#pID", PID[0]);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = selectAll;
DataSet ds = new DataSet();
adapter.Fill(ds);
connString.Close();
DataTable table = ds.Tables[0];
Yes you can include all ids in one parameter and get results that match them:
var parameters = new string[PID.Length];
var selectAll = new SqlCommand();
for (int i = 0; i < PID.Length; i++)
{
parameters[i] = string.Format("#Age{0}", i);
selectAll .Parameters.AddWithValue(parameters[i], PID[i]);
}
selectAll.CommandText = string.Format("SELECT * from Property p WHERE p.id IN ({0})", string.Join(", ", parameters));
selectAll.Connection = connString;
connString.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = selectAll;
DataSet ds = new DataSet();
adapter.Fill(ds);
connString.Close();
DataTable table = ds.Tables[0];

Categories