Delete row from datagridview - c#

I having problem on deleting a row of data returned by a search query.
I wish the user can select whichever row of data and click on the delete button [button1_click] to delete it from DB. This is a windows form application.
Hope you can advise me. Thanks a lot.
Below is my code
public partial class Search : Form
{
public Search()
{
InitializeComponent();
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable ds = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM staff", cn))
{
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
adp.Fill(ds);
comboBox1.DataSource = ds;
comboBox1.ValueMember = "sname";
comboBox1.SelectedIndex = 0;
}
}
}
private void btn_search_bystaffname_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE sname = #sname", cn))
{
//cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void btn_search_bydate_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
}
}

I'm assuming this is the method you want to change
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
This GridView1.Rows.Remove(row); will only remove the item from the DaDataGridViewRowCollection and will not remove it from the database.
To remove it from the database you can do one of the following
Remove it from `DataTable' and then use a DataAdapter and call update.
Directly delete it from the database using a DELETE SQL statement through a OleDbCommand.
If you choose option one you'd be well served by making dt a Field on your Form. This is because you can only access it now via ((DataRow)row.DataBoundItem).Table or GridView1.DataSource in the button1_Click event. Also making the DataAdapter a field would make this easier
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
Adapter.Update(dt);
As an aside you can choose to do only the dt.Rows.Remove(dRow); in the button1_Click and defer the Adapter.Update(dt) until later in a Save button.
If you go with option two you'll need to remove it from the DataTable or refresh the DataTable
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
OleDbCommand cmd = new OleDbCommand(
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
// not 100% this delete syntax is correct for Access
using (var cmd = new OleDbCommand("DELETE booking WHERE [Booking ID] = #BookingId", cn))
{
cmd.Parameters.AddWithValue("#BookingId", dRow["Booking Id"]);
cmd.ExecuteNonQuery();
}
}
// Do this to update the in-memory representation of the Data
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
// Or just refresh the datatable using code similar as your search methods

Here's how I've been doing it in my application (My unique identifier for the mysql table is in cell zero):
Oh, and dtcommand is a class instance for a database command class I use for common db stuff.
int userDeleteIndex;
if (int.TryParse(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), out userDeleteIndex))
{
if (MessageBox.Show("Delete " + recordidentifyingdata + "? ", "Delete " + userDeleteIndex.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
string updateUserSql = "DELETE FROM table WHERE user_id = " + userDeleteIndex.ToString() + "; ";
dtCommand.UpdateTable(updateUserSql);
InitializeUserDataView();
// Initalize userdataview refreshes the datagridview with the updated info
}
catch (Exception err)
{
Error trapping goes here
}
Here's the database update section from my class:
public int UpdateTable(string updateString, string MySqlConnectionString)
{
int returnValue = 0;
MySqlConnection connection = new MySqlConnection(MySqlConnectionString);
MySqlCommand command = new MySqlCommand(updateString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception err)
{
WriteErrorLog("Unable to update table: " + err.ToString() +
" - Using SQL string: " + updateString + ".");
//MessageBox.Show("An error has occured while updating the database.\n" +
//"It has been written to the file: " + errorFile + ".", "Database Error");
returnValue = -1;
}
finally
{
connection.Close();
}
return (returnValue);
}

Related

C# How to Save multiple rows from Datagridview to One Database

I have 2 datagridview and need to save them in one database.
I don't know how to explain this, but here I link the video I made directly from my desktop.
Youtube video link
And here my Save Button code for this form.
{
public Invoices()
{
InitializeComponent();
}
MySqlConnection Connection = new MySqlConnection("server=localhost; database=lmsdb; user=root; password=; pooling = false; convert zero datetime=True");
//MySqlConnection Connection = new MySqlConnection("server=35.186.146.59;database=lmsdb;uid=lmsdb;pwd=dbserver; pooling = false; convert zero datetime=True");
BindingSource bsInvoices = new BindingSource();
private void Invoices_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
MySqlConnection Connection = new MySqlConnection("server=localhost; database=lmsdb; user=root; password=; pooling = false; convert zero datetime=True");
//Connection.Open();
MySqlCommand Command = new MySqlCommand("Select * From invoicesdb", Connection);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(Command);
da.Fill(dt);
dgvInvoiceList.DataSource = null;
dgvInvoiceList.AllowUserToAddRows = false;
dgvInvoiceList.AutoGenerateColumns = false;
dgvInvoiceList.ColumnCount = 16;
dgvInvoiceList.Columns[0].HeaderText = "ID";
dgvInvoiceList.Columns[0].DataPropertyName = "id";
dgvInvoiceList.Columns[1].HeaderText = "Client Name";
dgvInvoiceList.Columns[1].DataPropertyName = "ClientName";
dgvInvoiceList.Columns[2].HeaderText = "References No";
dgvInvoiceList.Columns[2].DataPropertyName = "ReferencesNo";
dgvInvoiceList.Columns[3].HeaderText = "Case No";
dgvInvoiceList.Columns[3].DataPropertyName = "CaseNo";
dgvInvoiceList.Columns[4].HeaderText = "NRIC No";
dgvInvoiceList.Columns[4].DataPropertyName = "NRICNo";
dgvInvoiceList.Columns[5].HeaderText = "GST No";
dgvInvoiceList.Columns[5].DataPropertyName = "GSTNo";
dgvInvoiceList.Columns[6].HeaderText = "Invoices Date";
dgvInvoiceList.Columns[6].DataPropertyName = "InvoicesDate";
dgvInvoiceList.Columns[7].HeaderText = "Invoices Tax No";
dgvInvoiceList.Columns[7].DataPropertyName = "InvoicesTaxNo";
dgvInvoiceList.Columns[8].HeaderText = "Issue Date";
dgvInvoiceList.Columns[8].DataPropertyName = "IssueDate";
dgvInvoiceList.Columns[9].HeaderText = "Due Date";
dgvInvoiceList.Columns[9].DataPropertyName = "DueDate";
dgvInvoiceList.Columns[10].HeaderText = "Legal Fees";
dgvInvoiceList.Columns[10].DataPropertyName = "LegalFees";
dgvInvoiceList.Columns[11].HeaderText = "Stage";
dgvInvoiceList.Columns[11].DataPropertyName = "StageSchedule";
dgvInvoiceList.Columns[12].HeaderText = "Description";
dgvInvoiceList.Columns[12].DataPropertyName = "Description";
dgvInvoiceList.Columns[13].HeaderText = "Legal Fees Total";
dgvInvoiceList.Columns[13].DataPropertyName = "LegalFeesTotal";
dgvInvoiceList.Columns[14].HeaderText = "Disbursement Total";
dgvInvoiceList.Columns[14].DataPropertyName = "DisbursementTotal";
dgvInvoiceList.Columns[15].HeaderText = "Grand Total";
dgvInvoiceList.Columns[15].DataPropertyName = "GrandTotal";
dgvInvoiceList.Columns[0].Visible = false;
dgvInvoiceList.DataSource = dt;
Connection.Close();
MySqlConnection Connection2 = new MySqlConnection("server=localhost; database=lmsdb; user=root; password=; pooling = false; convert zero datetime=True");
//Connection.Open();
MySqlCommand Command2 = new MySqlCommand("Select * From invoicesdb", Connection2);
DataTable dt2 = new DataTable();
MySqlDataAdapter da2 = new MySqlDataAdapter(Command2);
da2.Fill(dt2);
dgvDisList.DataSource = null;
dgvDisList.AllowUserToAddRows = false;
dgvDisList.AutoGenerateColumns = false;
dgvDisList.ColumnCount = 2;
dgvDisList.Columns[0].HeaderText = "Description";
dgvDisList.Columns[0].DataPropertyName = "DisbursementDescription";
dgvDisList.Columns[1].HeaderText = "Amount";
dgvDisList.Columns[1].DataPropertyName = "DisbursementAmount";
dgvDisList.DataSource = dt2;
Connection2.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection Connection = new MySqlConnection("server=localhost; database=lmsdb; user=root; password=; pooling = false; convert zero datetime=True");
for (int i = 0; i < dgvDisList.Rows.Count; i++)
{
string disDescription = dgvDisList.Rows[i].Cells[0].Value.ToString();
string disAmount = dgvDisList.Rows[i].Cells[1].Value.ToString();
MySqlCommand cmd = new MySqlCommand($"INSERT INTO invoicesdb (id, ClientName, ReferencesNo, CaseNo, NRICNo, GSTNo, InvoicesDate, InvoicesTaxNo, IssueDate, DueDate, LegalFees, StageSchedule, Description, DisbursementDescription, DisbursementAmount, LegalFeesTotal, DisbursementTotal, GrandTotal) Values ('{tbID.Text}', {tbClientName.Text}','{tbReferencesNo.Text}','{tbCaseNo.Text}','{tbNRICNo.Text}','{tbGST.Text}','{dateInvoice.Text}','{tbInvoiceTaxNo.Text}','{dateIssue.Text}','{dateDue.Text}', '{tbLegalFees.Text}','{cbStageSchedule.Text}','{tbDescription.Text}','{ disDescription }','{ disAmount }','{tbTotalLegalFees.Text}','{tbTotalDisbursement.Text}','{tbGrandTotal.Text}')", Connection);
Connection.Open();
cmd.ExecuteNonQuery();
Connection.Close();
}
Invoices_Load(sender, e);
MessageBox.Show("Saved Successfully");
btnNew_Click(sender, e);
}
}
}
You will need to import the following namespaces.
using System.Data;
using System.Data.SqlClient;
Inside the Form Load event, the DataGridView is populated with a dynamic DataTable
private void Form1_Load(object sender, EventArgs e)
{
this.BindDataGridView();
}
private void BindDataGridView()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new .....
a loop is executed over the DataGridView rows. Inside the loop, the values from each column (cell) of the DataGridView are fetched and the record is inserted into the database table.

Combobox in a datagridview

I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.

Displaying datagridview records depending on button selected

I'm making a form in c# where the datagridveiw displays the records from the database depending on what floor is selected. same with this
The problem is after I created my code, I always get an error: ColumnCount property cannot be set on a data-bound DataGridView control.
Can anyone give me an idea on how to make it possible to display the database records depending on button selected.
Anyway, this is my code below.
private void button4_Click(object sender, EventArgs e)
{
using (NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=1234;Database=postgres;"))
{
using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM information WHERE college = 'cbaa' AND floor = '1'", conn))
{
cmd.CommandType = CommandType.Text;
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView2.AutoGenerateColumns = false;
dataGridView2.ColumnCount = 5;
dataGridView2.Columns[0].Name = "roomNum";
dataGridView2.Columns[0].HeaderText = "Room No.";
dataGridView2.Columns[0].DataPropertyName = "roomNum";
dataGridView2.Columns[1].Name = "type";
dataGridView2.Columns[1].HeaderText = "Room Type";
dataGridView2.Columns[1].DataPropertyName = "type";
dataGridView2.Columns[2].Name = "sIllumination";
dataGridView2.Columns[2].HeaderText = "Standard Illumination";
dataGridView2.Columns[2].DataPropertyName = "sIllumination";
dataGridView2.Columns[3].Name = "aIllumination";
dataGridView2.Columns[3].HeaderText = "Actual Illumination";
dataGridView2.Columns[3].DataPropertyName = "aIllumination";
dataGridView2.Columns[4].Name = "difference";
dataGridView2.Columns[4].HeaderText = "Difference";
dataGridView2.Columns[4].DataPropertyName = "difference";
dataGridView2.DataSource = dt;
}
}
}
}
}
private void button5_Click(object sender, EventArgs e)
{
using (NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=1234;Database=postgres;"))
{
using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM information WHERE college = 'cbaa' AND floor = '2'", conn))
{
cmd.CommandType = CommandType.Text;
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView2.AutoGenerateColumns = false;
dataGridView2.ColumnCount = 5;
dataGridView2.Columns[0].Name = "roomNum";
dataGridView2.Columns[0].HeaderText = "Room No.";
dataGridView2.Columns[0].DataPropertyName = "roomNum";
dataGridView2.Columns[1].Name = "type";
dataGridView2.Columns[1].HeaderText = "Room Type";
dataGridView2.Columns[1].DataPropertyName = "type";
dataGridView2.Columns[2].Name = "sIllumination";
dataGridView2.Columns[2].HeaderText = "Standard Illumination";
dataGridView2.Columns[2].DataPropertyName = "sIllumination";
dataGridView2.Columns[3].Name = "aIllumination";
dataGridView2.Columns[3].HeaderText = "Actual Illumination";
dataGridView2.Columns[3].DataPropertyName = "aIllumination";
dataGridView2.Columns[4].Name = "difference";
dataGridView2.Columns[4].HeaderText = "Difference";
dataGridView2.Columns[4].DataPropertyName = "difference";
dataGridView2.DataSource = dt;
}
}
}
}
}
Thanks in advance!

Connect BindingNavigator with Programmatically Created Datagridview

I have created a datagridview programmatically.
So there is no bindingsource or datasource that we can connect both of the Datagridview and Binidgnavigator to them.
Is there any other way to connect them to each other.
Here is my code for datafridview
Help me to connect it to a bindingNavigator
private void Fill()
{
try
{
if (dataGridView1 != null)
{
dataGridView1.ColumnCount = 11;
dataGridView1.Columns[0].HeaderText = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].HeaderText = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].HeaderText = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].HeaderText = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].HeaderText = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].HeaderText = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].HeaderText = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].HeaderText = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].HeaderText = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].HeaderText = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].HeaderText = Resources.Form1_Fill_Address;
dataGridView1.Columns[0].Name = Resources.Form1_Fill_ID;
dataGridView1.Columns[1].Name = Resources.Form1_Fill_Family;
dataGridView1.Columns[2].Name = Resources.Form1_Fill_Cellphone;
dataGridView1.Columns[3].Name = Resources.Form1_Fill_Phone1;
dataGridView1.Columns[4].Name = Resources.Form1_Fill_Phone2;
dataGridView1.Columns[5].Name = Resources.Form1_Fill_Phone3;
dataGridView1.Columns[6].Name = Resources.Form1_Fill_Fax;
dataGridView1.Columns[7].Name = Resources.Form1_Fill_CompanyName;
dataGridView1.Columns[8].Name = Resources.Form1_Fill_Agency;
dataGridView1.Columns[9].Name = Resources.Form1_Fill_Brands;
dataGridView1.Columns[10].Name = Resources.Form1_Fill_Address;
}
_conn.ConnectionString = _connectionString;
var cmd = new OleDbCommand("Select * from contacts ", _conn);
_conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader != null && reader.Read())
{
if (dataGridView1 != null)
{
dataGridView1.Rows.Add(1);
}
if (dataGridView1 != null)
{
var row = dataGridView1.Rows[i];
row.Cells[Resources.Form1_Fill_ID].Value = reader[0].ToString();
row.Cells[Resources.Form1_Fill_Family].Value = reader[1].ToString();
row.Cells[Resources.Form1_Fill_Cellphone].Value = reader[2].ToString();
row.Cells[Resources.Form1_Fill_Phone1].Value = reader[3].ToString();
row.Cells[Resources.Form1_Fill_Phone2].Value = reader[4].ToString();
row.Cells[Resources.Form1_Fill_Phone3].Value = reader[5].ToString();
row.Cells[Resources.Form1_Fill_Fax].Value = reader[6].ToString();
row.Cells[Resources.Form1_Fill_CompanyName].Value = reader[7].ToString();
row.Cells[Resources.Form1_Fill_Agency].Value = reader[8].ToString();
row.Cells[Resources.Form1_Fill_Brands].Value = reader[9].ToString();
row.Cells[Resources.Form1_Fill_Address].Value = reader[10].ToString();
}
i++;
}
}
catch (Exception ex)
{
return;
}
finally
{
_conn.Close();
}
}
Try to revise your code. You don't need to create a column programmactically, your query itself could create a column through DataTable to BindingSource, try this code and get some idea.
BindingNavigator and BindingSource
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=D:\myDatabase.accdb;";
string queryString = "SELECT Name AS FullName, Gender AS Gender, Address AS [Current Address] FROM Person";
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(queryString, connection))
{
try
{
BindingSource bs = new BindingSource();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(queryString, connection);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
bs.DataSource = dataTable;
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

different window.open opens the same page

I am using window.open to open 2 different pages in pop-up windows,but for some reason both the triggers opens the same page in the pop-up window,heres how I am trying to do this:
first:
Response.Write("<script type='text/javascript'>window.open('TransEditEntry.aspx','mywindow','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
second:
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
this opens 'TransEditEntry.aspx' page instead of 'TransNewEntry.aspx'`
here the rest of the code:
The entire function which is called on add button click:
protected void addNew(object sender, EventArgs e)
{
//HiddenField sr = (HiddenField)GridView1.SelectedRow.Cells[6].FindControl("srno");
//Session["TransSrNo"] = sr.Value;
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
//Session["transAdd"] = "1";
}
The add button which calls the function:
<asp:Button ID="AddBtn" runat="server" OnClick="addNew" Text="Add"/>
The page TransNewEntry.aspx.cs
public partial class TransEditEntry : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(GetConnectionString.Get());
string subCode;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder build;
DataRow dr;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
Response.Write((Session["TransSrNo"]).ToString());
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
con.Open();
SqlCommand cmd3 = new SqlCommand("select sub_code from tran_dtls where sr_no='" + SRno + "'", con);
subCode = (string)cmd3.ExecuteScalar();
con.Close();
if (!IsPostBack)
{
sda = new SqlDataAdapter("select * from tran_dtls where sr_no=" + SRno + "", con);
build = new SqlCommandBuilder(sda);
dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
srNoTxt.Text = "";
amttxt.Text = "";
partTxt.Text = "";
checkNoTxt.Text = "";
checkDtTxt.Text = "";
refNoTxt.Text = "";
refDtTxt.Text = "";
jobNoTxt.Text = "";
}
}
}
protected void GlChange(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd4 = new SqlCommand("select ac_type from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string acType = (string)cmd4.ExecuteScalar();
SqlCommand cmd5 = new SqlCommand("select gl_code from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string gl_code = (string)cmd5.ExecuteScalar();
if (acType == "S")
{
SqlDataSource3.SelectCommand = ("select ac_desc from ac_mstr where gl_code='" + gl_code + "'");
subDrp.DataBind();
subDrp.Enabled = true;
//Response.Write("<script type='javacript/text'>alert('1')</script>");
}
else
{
subDrp.Enabled = false;
//Response.Write("<script type='javacript/text'>alert('2')</script>");
}
con.Close();
}
protected void saveRow(object sender, EventArgs e)
{
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
sda = new SqlDataAdapter("select * from tran_dtls where tc='" + Session["TC"] + "' and doc_no='" + Session["docNo"] + "' ", con);
build = new SqlCommandBuilder(sda);
//dt = new DataTable();
// DataSet ds = new DataSet();
sda.Fill(ds);
dt = (DataTable)ViewState["myViewState"];
if (Session["gridRow"] == null)
{
dt = ds.Tables[0];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
else
{
dt = (DataTable)Session["gridRow"];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
//Response.Write("<script type='text/javascript'>window.opener.location.reload(true);</script>");
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
}
private void closeFunction()
{
StringBuilder sb = new StringBuilder();
sb.Append("window.opener.RefreshPage();");
sb.Append("window.close();");
ClientScript.RegisterClientScriptBlock(this.GetType(), "CloseWindowScript", sb.ToString(), true);
}
}
Check your condition where you are doing : Response.Write. Both the conditions must be pointing out for first>

Categories