Delete Multiple selected row in radgridview and also delete row in database winform C# - telerik

Haha.. i don't know how to delete data based on selected row in radgridview and also delete it in mysql. this is going to be a confusing school assignment, does anyone know how to solve it?
this is the line of code i made:
private void A_3_BtnDelete_Click_1(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["GreatRetail_connect"].ConnectionString;
string query = "DELETE FROM tb_stock_product WHERE ID_product= ID_product ";
MySqlConnection conn = new MySqlConnection(mainconn);
for (int i = 0; i < RAD_GridView_ShowData.SelectedRows.Count - 1; i++)
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("ID_product", RAD_GridView_ShowData.SelectedRows[i].Cells[0].Value.ToString());
MySqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
MessageBox.Show("Delete data sucsessfully");
conn.Close();
ShowData();
}
}
it would be great today if anyone would like to help.

Related

Transacrtion commit and rollback not working using OracleTransaction

I had search in the internet and not much info I can get. I try to insert data to table database oracle, but it's not working when I use OracleConnection and OracleTransaction to commit and rollback. the following code ;
using (Entities dbContext = new Entities())
{
string constr = "data source=10.10.10.228:1521/MPMBO;password=tax;user id=TAX";
using (OracleConnection orcConnect = new OracleConnection(constr))
{
orcConnect.Open();
OracleCommand orcCommand = orcConnect.CreateCommand();
OracleTransaction orcTransaction;
orcTransaction = orcConnect.BeginTransaction(IsolationLevel.ReadCommitted);
orcCommand.Transaction = orcTransaction;
try
{
MPMISTAX_HDRMASUK item = new MPMISTAX_HDRMASUK();
//something item to include...
dbContext.MPMISTAX_HDRMASUK.Add(item);
dbContext.SaveChanges();
for (int j = 0; j < Id.Length; j++)
{
MPMISTAX_DTLMASUK itemA = new MPMISTAX_DTLMASUK();
//something code
dbContext.MPMISTAX_DTLMASUK.Add(itemA);
}
dbContext.SaveChanges();
orcTransaction.Commit();
}
catch (Exception dbEx)
{
orcTransaction.Rollback();
throw new Exception(dbEx.Message);
}
}}
I can't get error, but the table not insert in database oracle. I hope you can help my problem. Thank you

Implementation Add Connection of Visual Studio

I want to create Connect To DataBase form(Something like Visual Studio 2012 Add Connection
I find this code to find Connected server
private void FillServerComboBox()
{
DataTable ServersTable = new DataTable();
SqlDataSourceEnumerator servers = SqlDataSourceEnumerator.Instance;
ServersTable = servers.GetDataSources();
object[] obj = new object[ServersTable.Rows.Count];
for (int i = 0; i < ServersTable.Rows.Count; i++)
{
obj[i] = string.Format("{0}\\{1}", ServersTable.Rows[i]["ServerName"].ToString(), ServersTable.Rows[i]["InstanceName"].ToString());
}
serversComboBox.DataSource = obj;
}
And I find "Master.dbo.sp_Databases" procedure to list databases on remote server. But I do not have permission on MasterTable. How does "Add Connection Form" work on Visual Studio?
But it does not work. Please guide me on that!
I found an asnwer
SqlConnection _SqlConnection = new SqlConnection(ConnectionString);
_SqlConnection.Open();
DataTable dt1 = _SqlConnection.GetSchema("Tables");
and
SqlConnection _SqlConnection = new SqlConnection(ConnectionString);
_SqlConnection.Open();
DataTable dt1 = _SqlConnection.GetSchema("DataBases");

Comparing very large List<string> with database table via LINQ to Entities

I have a very large list of strings containing GUIDs and a 100,000+ record table in a database with an Entity Framework model in my app.
What' is the most efficient approach to finding all records in a particular dataset where the GUID List is not present?
The following is performing very slowly:
var list= new List<string> { "1", "2", "3" };
return (from t1 in db.Items
where (!list.Contains(t1.GUID))
When I have a lot of parameters (several hundreds or more) to a query I use bulk insert to temporary table and then join it from main table.
My code looks something like this:
private static DataTable FillDataTable(IEnumerable<int> keys) {
var dataTable = new DataTable("Stage");
dataTable.Locale = CultureInfo.CurrentCulture;
dataTable.Columns.Add("Key", typeof(int));
foreach (var key in keys) {
var row = dataTable.NewRow();
row[0] = key;
dataTable.Rows.Add(row);
}
return dataTable;
}
private static void CreateStageTable(SqlConnection connection, string tableName, DataTable dataTable) {
var sql = new StringBuilder();
sql.AppendLine("CREATE TABLE {StageTableName} ( ");
sql.AppendLine(" Key INT NOT NULL ");
sql.AppendLine(") ");
sql.Replace("{StageTableName}", SqlUtilities.QuoteName(tableName));
using (var command = connection.CreateCommand()) {
command.CommandText = sql.ToString();
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
using (var bulkcopy = new SqlBulkCopy(connection)) {
bulkcopy.DestinationTableName = tableName;
bulkcopy.WriteToServer(dataTable);
}
}
public void DoQuery(IEnumerable<int> keys) {
var dataTable = FillDataTable(keys);
using (var connection = new SqlConnection(_connectionString)) {
connection.Open();
CreateStageTable(connection, "#Stage", dataTable);
string sql = "SELECT x " +
"FROM tbl " +
" LEFT JOIN {StageTableName} AS Stage " +
" ON x.Key = Stage.Key "
"WHERE Stage.Key IS NULL";
...
}
}
Don't use a List, use a HashSet<string>, this will give you O(1) lookup ups instead of O(n).

How to read Excel cells and write to database

I am writing an C# application that reads from an an excel sheet. It reads the whole sheet, however I am interested in just reading particular cells in a row and move to the next row and read particular cells in that row again. Cells not read or omitted are the same for all rows in excel. Below is my sample code for reading excel:
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:/test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for(int i=1; i <= rowCount; i++)
{
for(int j=1; j<=colCount; j++)
{
MessageBox.Show(xlRange.Cells[i,j].Value2.ToString());
}
}
}
You could use OleDB instead of Excel.Interop. Your question requires only reading cell values so it is easier to treat your excel file as a datatable itself....
string fileName = #"C:\test.xlsx";
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0'", fileName);
using(OleDbConnection cn = new OleDbConnection(connectionString))
{
cn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Column1, Column2, Column3 From [Sheet1$]", cn);
OleDbDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
Console.WriteLine("Loop");
Console.WriteLine(rd.GetString(0));
Console.WriteLine(rd.GetString(1));
Console.WriteLine(rd.GetString(2));
Console.WriteLine();
}
}
A couple of notes:
I'm using ACE.OleDB because your file has XLSX extensions
I'm assuming your file has Column headers in the first line called Column1. etc....

How do i add a row at the end of a DataGridview?

I have a datagridview2 on my form that has 4 columns and has data. I want to add a row at the end of it and fill it with data. But when i use 'Me.DataGridView2.Rows.Add()' it adds row but not the end of the datagridview. is there a way to add a blank row at the end of datagridview?
The last row in datagridview is to allow user to add row if he wants.
Set DataGridView2.AllowUserToAddRows = False
Then try to use Me.DataGridView2.Rows.Add() . It will Add a raw to the end of the
dataGridView
I would upvote #user1157690, but I don't have enough reputation to do so. In order to add a blank row to the bottom:
DataGridView2.AllowUserToAddRows = false;
for (int i = 0; i < 10; i++)
{
DataGridView2.Rows.Add();
}
DataGridView2.AllowUserToAddRows = true;
This would allow you to enter 10 blank rows programmatically in chronological order from oldest to newest while allowing the user to enter additional rows if necessary. This is the best method that I know of for allowing user flexibility and programmer consistency.
I tried and it adds the row at the end of the DataGridView.
I dragged a DataGridView and a button in the form.
Here is the code:
private void addRowbutton_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("ID", "Product ID");
dataGridView1.Columns.Add("Name", "Product Name");
dataGridView1.Columns.Add("Description", "Description");
dataGridView1.Columns.Add("Price", "Price");
for (int i = 0; i < 2; i++)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1);
row.Cells[0].Value = i;
row.Cells[1].Value = "Product " + i;
row.Cells[2].Value = "Description of Product " + i;
row.Cells[3].Value = "99.99";
dataGridView1.Rows.Add(row);
}
}
If you populate the datagridview via databind you cannot add a row programmatically.

Resources