How to Delete Row By ID From Datatable and Database - c#

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);

Related

Read and display selected rows in datatable

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.

C#: Add "Select" item to Dynamic Fill ComboBox method

I need to add "Select" at index 0 without know DataTable columns count or name because this method in DataAccessLayer and will use later`
// ComboBox Fill Method
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
I have solved this issue by the following code.
Thanks for all ...
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drow = dt.NewRow();
for (int i = 0; i < dt.Columns.Count ; i++)
{
if (dt.Columns[i].ColumnName == cboDisplayMember)
{
drow[i] = "Select";
}
else if (dt.Columns[i].ColumnName == cboValueMember)
{
drow[i] = 0;
}
else
{
drow[i] = null;
}
}
dt.Rows.InsertAt(drow, 0);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
Just put this line in your ComboBoxFill() function.
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
DataRow newRow = dt.NewRow();
newRow[0] = "Select";
dt.Rows.InsertAt(newRow, 0);
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
It will add "Select" at postion 0

sum up data from Access to DataTable

I have a database that contains a Column of 3 Defined Types and a Column of that contains numbers.
The types can appear severl time in the database.
I want to create a DataTable that will show each type one time only and sum up to numbers that relate to that type.
List<String> types = typesInTable(table);
DataTable t = new DataTable();
t.Clear();
t.Columns.Add("Type");
t.Columns.Add("Total Expenses");
foreach (String type in types)
{
DataRow tmp = t.NewRow();
tmp["Type"] = type;
int total = 0;
myConnection.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Type] , [Expense] FROM [" + table+"]", myConnection);
reader = cmd.ExecuteReader();
while (reader.Read())
{
if(reader["Type"].ToString().Equals(type))
{
total += Convert.ToInt32(reader["Expense"].ToString());
}
}
tmp["Total Expenses"] = total;
if (!t.Rows.Contains(tmp))
{
t.Rows.Add(tmp);
}
myConnection.Close();
}
This Code makes the types appear several times.
You can use this code to create DataTable that contains every type grouped with the sum :
DataTable t = new DataTable();
myConnection.Open();
string query = string.Format("SELECT Type, Sum(Expense) AS TotalExpenses FROM [{0}] group by Type", table);
OleDbCommand cmd = new OleDbCommand(query, myConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(t);
myConnection.Close();
if You want to sum up the types from different tables all together in 1 DataTable use this:
List<String> tableList = serviceMethod.getTableList();
DataTable dtAllType = new DataTable();
foreach (string table in tableList)
{
DataTable dtTemp = new DataTable();
myConnection.Open();
string query = string.Format("SELECT Type, Sum(Expense) AS TotalExpenses FROM [{0}] group by Type", table);
OleDbCommand cmd = new OleDbCommand(query, myConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dtTemp);
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
bool isDupe = false;
for (int j = 0; j < dtAllType.Rows.Count; j++)
{
if (dtTemp.Rows[i][0].ToString() == dtAllType.Rows[j][0].ToString())
{
dtAllType.Rows[j][1] = int.Parse(dtAllType.Rows[j][1].ToString()) + int.Parse(dtTemp.Rows[i][1].ToString());
isDupe = true;
break;
}
}
if (!isDupe)
{
dtAllType.ImportRow(dtTemp.Rows[i]);
}
}
myConnection.Close();
}
the dtAllType DataTable contain Type grouped with sum of Expence

How to show all the rows in datagridview?

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;

Adding a column to a datatable and adding data

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

Categories