Combobox in a datagridview - c#

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.

Related

How can I search a listbox items depending on a variable?

I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}

keydown Event can't add item in datagridview

When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically

Can not get last selected item in DataGridViewComboBoxCell

my problem is like that: I have a C# application having datagridview which has some textboxes and comboboxes in its columns. All the columns get the data from a database. Textboxes are readonly. When i ask for values in each row, i get the last selected component's value (i.e. combobox' value because textboxes are readonly) as null.
For example:
I have 10 cells in a row. The comboboxes are at 7th, 8th and 9th indexes in a row, where indexes from 0 to 6 are texboxes. When i select 3 of them (in order of 7, 8, 9) i cannot get the cell value of 9.
row.Cells[7].Value is OK,
row.Cells[8].Value is OK, and
row.Cells[9].Value is null
When i select any two of them let say first 8 and then 7, i cannot get the cell value of 7.
row.Cells[8].Value is OK and
row.Cells[7].Value is null
When i select only one item let say 9, i got the cell value again null.
As a result i get the last selected DataGridViewComboBoxCell as null.
Can anyone help me in my problem please? Thanks for all your help.
Here is my code:
private void cmbVariable_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = sender as ComboBox;
BringQuery(cmb.SelectedItem.ToString());
}
private void BringQuery(string option)
{
SqlConnection conn = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
DataTable dt1 = new DataTable();
SqlCommand cmd1 = new SqlCommand("select Track_Number, Parking_Area, Mission_Number, Track_Info, Time, Direction, Explanation from Traffic_Run_Table where Op_Type=#myType", conn);
SqlCommand cmd2 = new SqlCommand("select * from Traffic_Track_Table", conn);
SqlCommand cmd3 = new SqlCommand("select * from Traffic_Driver order by Id_Number", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
cmd1.Parameters.Add(new SqlParameter("myType", option));
try
{
conn.Open();
sda1.Fill(dt1);
dataGridView2.AutoGenerateColumns = false;
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.DataPropertyName = col.Name;
}
dataGridView2.DataSource = dt1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
DataGridViewComboBoxColumn cmbCol1, cmbCol2, cmbCol3;
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
try
{
cmbCol1 = new DataGridViewComboBoxColumn();
cmbCol1.HeaderText = "Track 1";
cmbCol1.Name = "Track1";
cmbCol1.DataPropertyName = cmbCol1.Name;
cmbCol1.ValueType = typeof(int);
cmbCol1.Width = 50;
cmbCol2 = new DataGridViewComboBoxColumn();
cmbCol2.HeaderText = "Track 2";
cmbCol2.Name = "Track2";
cmbCol2.DataPropertyName = cmbCol2.Name;
cmbCol2.ValueType = typeof(int);
cmbCol2.Width = 50;
sda2.Fill(dt2);
dt2.Columns[0].ColumnName = "Track";
foreach (DataRow dr in dt2.Rows)
{
cmbCol1.Items.Add(Convert.ToInt32(dr["Track"]));
cmbCol2.Items.Add(Convert.ToInt32(dr["Track"]));
}
dataGridView2.Columns.Add(cmbCol1);
dataGridView2.Columns.Add(cmbCol2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlDataAdapter sda3 = new SqlDataAdapter(cmd3);
DataTable dt3 = new DataTable();
try
{
cmbCol3 = new DataGridViewComboBoxColumn();
cmbCol3.HeaderText = "Driver";
cmbCol3.Name = "Driver";
cmbCol3.DataPropertyName = cmbCol3.Name;
cmbCol3.ValueType = typeof(string);
cmbCol3.Width = 260;
sda3.Fill(dt3);
dt3.Columns[0].ColumnName = "Id";
dt3.Columns[1].ColumnName = "Driver";
dt3.Columns[2].ColumnName = "Mission";
foreach (DataRow dr in dt3.Rows)
{
cmbCol3.Items.Add(Convert.ToString(dr["Id"]).Trim() + " - " + Convert.ToString(dr["Dirver"]).Trim() + " - " + Convert.ToString(dr["Mission"]).Trim());
}
dataGridView2.Columns.Add(cmbCol3);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
public string CheckNull(object value, Type objType)
{
string retVal = string.Empty;
if (value == null || value.ToString() == " " || value.ToString() == "")
{
if (objType == typeof(int))
{
retVal = "0";
}
if (objType == typeof(string))
{
retVal = "-";
}
}
else
{
retVal = value.ToString();
}
return retVal;
}
private void Save_Click(object sender, EventArgs e)
{
SqlConnection connForSave = new SqlConnection("Server = 10.2.6.14; Database = TTS; uid = myuser; password = mypassword");
SqlCommand cmdForSave = new SqlCommand("insert into Traffic_Records values (#type, #trackNumber, #parkingArea, #missionNmb, #trackInfo, #time, #direction, #explanation, #track1, #track2, #driverId, #driverName, #driverMission, #date)", connForSave);
foreach (DataGridViewRow row in dataGridView2.Rows)
{
try
{
dataGridView2[7, row.Index].Selected = false;
dataGridView2[8, row.Index].Selected = false;
dataGridView2[9, row.Index].Selected = false;
connForSave.Open();
cmdForSave.Parameters.AddWithValue("type", CheckNull(cmbVairable.SelectedItem.ToString(), typeof(string)));
cmdForSave.Parameters.AddWithValue("trackNumber", Convert.ToInt16(CheckNull(row.Cells[0].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("parkingArea", CheckNull(row.Cells[1].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("missionNmb", Convert.ToInt16(CheckNull(row.Cells[2].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("trackInfo", CheckNull(row.Cells[3].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("time", CheckNull(row.Cells[4].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("direction", CheckNull(row.Cells[5].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("explanation", CheckNull(row.Cells[6].Value, typeof(string)));
cmdForSave.Parameters.AddWithValue("track1", Convert.ToInt16(CheckNull(row.Cells[7].Value, typeof(int))));
cmdForSave.Parameters.AddWithValue("track2", Convert.ToInt16(CheckNull(row.Cells[8].Value, typeof(int))));
string[] sArray = null;
if (string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "0") != 0 && string.Compare(CheckNull(row.Cells[9].Value, typeof(string)), "-") != 0)
{
sArray = row.Cells[9].Value.ToString().Split('-');
sArray[0] = sArray[0].Remove(sArray[0].Length - 2, 1);
sArray[1] = sArray[1].Remove(0, 1);
sArray[1] = sArray[1].Remove(sArray[1].Length - 2, 1);
sArray[2] = sArray[2].Remove(0, 1);
}
else
{
string temp = "0 - -";
sArray = temp.Split(' ');
}
cmdForSave.Parameters.AddWithValue("driverId", Convert.ToInt16(sArray[0]));
cmdForSave.Parameters.AddWithValue("driverName", sArray[1]);
cmdForSave.Parameters.AddWithValue("driverMission", sArray[2]);
cmdForSave.Parameters.AddWithValue("date", DateTime.Now);
cmdForSave.ExecuteNonQuery();
cmdForSave.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n Line Number: " + ex.LineNumber());
}
connForSave.Close();
}
}
This happens because DataGridView does not commit user made changes instantly but only after row is validated (I think, may be wrong here). So after you selected last value and did not change row (so validate event has not fired) the value in combo box is still null.
To fix this add CurrentCellDirtyStateChanged (more info here MSDN event to your grid:
private void GridCurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvAssignedProperties.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
and this why new values are committed right away.

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>

Delete row from datagridview

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

Categories