I have created a datatable that displays the data which is gathered from the datareader. My problem is it does not display all the rows that are being selected. It only displays one row.How can I display all the rows that are being selected?
Code Behind
int Quantity;
string JobName;
string OrderType;
DateTime DueDate;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string cmdText = "SELECT Quantity,Job_Name,[Order],Due_Date FROM Shopping_Cart WHERE UID=#UIDD";
SqlCommand cmd = new SqlCommand(cmdText, con);
//===== Adding parameters/Values.
cmd.Parameters.AddWithValue("#UIDD", hfUserID.Value);
//===== To check current state of the connection object. If it is closed open the connection
//===== to execute the insert query.
if (con.State == ConnectionState.Closed)
{
con.Open();
}
//===== Execute Query.
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Quantity = dr.GetInt32(0);
JobName = dr.GetString(1);
OrderType = dr.GetString(2);
DueDate = dr.GetDateTime(3);
con.Close();
if (Session["UID"] != null)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] {
new DataColumn("QUANTITY", typeof(string)),
new DataColumn("JOB NAME", typeof(string)),
new DataColumn("ORDER TYPE", typeof(string)),
new DataColumn("DUE DATE", typeof(string))});
dt.Rows.Add(Quantity, JobName, OrderType, DueDate);
YourTable.Append("<table border = '1'>");
YourTable.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
YourTable.Append("<th style = 'background-color: #0bd2d1;color:#ffffff'>");
YourTable.Append(column.ColumnName);
YourTable.Append("</th>");
}
YourTable.Append("</tr>");
foreach (DataRow row in dt.Rows)
{
YourTable.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
YourTable.Append("<td>");
YourTable.Append(row[column]);
YourTable.Append("</td>");
}
YourTable.Append("</tr>");
}
Rather than
dr.Read()
use
while(dr.Read())
{
// Do stuff
}
That way it will loop over all rows in the DataReader.
Related
it returns the value of approved column as "yes\0\0\0\0\0\0" instead of "yes"
public void getapproved()
{
SqlDataAdapter da = new SqlDataAdapter("select * from owner_addproperties", con);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dtoriginaltable =ds.Tables[0];
DataTable dtfinaltable = new DataTable();
foreach (DataColumn dc in dtoriginaltable.Columns)
{
dtfinaltable.Columns.Add(dc.ColumnName);
}
foreach (DataColumn dc in dtfinaltable.Columns)
{
if (dc.ColumnName == "approved")
dc.DataType = System.Type.GetType("System.Boolean");
}
foreach (DataRow drow in dtoriginaltable.Rows)
{
if (drow["approved"].Equals("yes"))
drow["approved"] = true;
else
drow["approved"] = false;
dtfinaltable.Rows.Add(drow.ItemArray);
}
gvadmin_owner_view.DataSource = dtfinaltable;
gvadmin_owner_view.DataBind();
}
Change
if (drow["approved"].Equals("yes"))
to
if (drow["approved"].ToString().StartsWith("yes"))
Here is full code at the moment what I have done. So basically I'm creating a DataTable, then I'm connecting my DataTable with a database. I can edit person by ID, but I don't know how to delete person by ID. I want a full row to be deleted.
As well, in the part where I edit the DataTable, if I choose not to edit table, I get some null reference error
Object reference not set to an instance of an object.
My code:
/*
* Creating DataTable
*/
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Vards", typeof(string)));
dt.Columns.Add(new DataColumn("Uzvards", typeof(string)));
/*
* Connecting to DataBase
*/
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM PERSONA", con);
con.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
DataRow dr = dt.NewRow();
dr["ID"] = dataReader["ID"];
dr["Vards"] = dataReader["Vards"];
dr["Uzvards"] = dataReader["Uzvards"];
dt.Rows.Add(dr);
}
con.Close();
dt.AcceptChanges();
PrintDataTable(dt);
Console.WriteLine();
/* Edit Person in DataTable */
Console.WriteLine("Kuru ID vēlaties labot?");
int labosana = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vai tiešām vēlaties labot šo ierakstu?");
string vaiLabot = Console.ReadLine();
if (vaiLabot == "yes")
{
Console.WriteLine("Ievadiet jauno vārdu:");
string vards = Console.ReadLine();
Console.WriteLine("Ievadiet jauno uzvārdu:");
string uzvards = Console.ReadLine();
dt.Rows[labosana-1]["Vards"] = vards;
dt.Rows[labosana-1]["Uzvards"] = uzvards;
}
else
{
Console.WriteLine("Jūs atteicāties labot!");
}
/*
* Adding Edited Person to Database
*/
OleDbCommand upCmd = new OleDbCommand("UPDATE PERSONA SET Vards=?,Uzvards=? WHERE ID=?", con);
upCmd.Parameters.Add(new OleDbParameter("#Vards",OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#Uzvards", OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.Integer));
foreach(DataRow dro in dt.GetChanges().Rows)
{
if (dro.RowState == DataRowState.Modified)
{
upCmd.Parameters[0].Value = dro[1];
upCmd.Parameters[1].Value = dro[2];
upCmd.Parameters[2].Value = dro[0];
con.Open();
upCmd.ExecuteNonQuery();
con.Close();
}
}
I tried a ton of code. But none of them seems to work. Tried something like this to delete by the Name.
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
dr.Delete();
}
Use this code for deleting by Id from database:
public int DeleteById(int Id)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("DELETE FROM PERSONA WHERE ID = #ID", con);
cmd.Parameters.Add(new OleDbParameter("ID", Id));
return cmd.ExecuteNonQuery();
}
Updated: try this -- To delete from the DataTable
DataRow rowToBeDeleted;
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
rowToBeDeleted = dr;
}
dt.Rows.Remove(rowToBeDeleted );
Or if using LINQ, you can also do something like
var dr = dt.AsEnumerable().Where(row => row.Field<string>("Vards") == "Name").SingleOrDefault();
dt.Rows.Remove(dr);
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;
How can I add a column to a datatable and add data to each row based on a condition.
This is what I am trying to do
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
Dictionary<string, string> items = new Dictionary<string, string>();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CODE, TITLE FROM tblProducts";
OleDbDataReader dbread = cmd.ExecuteReader();
while (dbread.Read())
{
productCode = (string)dbread["ProductCode"];
productTitle = items[productCode];
items.Add(productCode, productTitle);
}
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < items.Count; i++)
{
if (dr["ProductCode"].ToString().Equals(productCode))
{
//here I want to add a new column and add data (productTitle) to the column
}
}
}
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
dt.Columns.Add("ColumnName", typeof(DataType));
if (dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
Further i would extend the code to avoid NullReferenceException
if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx
I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();