I would like to get the value from ms access database to the checkedListBox.
it works properly for the ComboBox and TextBox but I don't know how to do that with the checkedListBox_prodline or checkedListBox_owner. (I have only one value in the database field)
private void button_clone_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * from PPAPdatabase where [PSW ID]=" + txt_c_PSW_ID.Text + "";
OleDbDataReader dr = null;
dr = command.ExecuteReader();
while (dr.Read())
{
comboBox_PPAP.Text = (dr["Reason"].ToString());
checkedListBox_prodline.Text = (dr["Production Line"].ToString());
checkedListBox_owner.Text = (dr["Owner"].ToString());
txt_comment.Text = (dr["Comment"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.Message,
"Important Note",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
finally
{
connection.Close();
}
Any help would be greatly appreciated!
Take a look of CheckedListBox.SetItemChecked. In case your items are strings.
var productLine = dr["Production Line"].ToString();
for (var i = 0; i < checkedListBox_prodline.Items.Count; i++)
{
var item = checkedListBox_prodline.Items[i] as string;
checkedListBox_prodline.SetItemChecked(i, productLine == item);
}
Related
I'm making a small program that allows me to insert data into a data table which is connected with PostgreSQL. All functions are working fine on postgresql: select, insert, update and delete.
Here is the code:
private void FrmTeachers_Load(object sender, EventArgs e)
{
conn = new NpgsqlConnection(connstring);
Select();
//dgvTabela.Columns["docente_id"].HeaderText = "Teachers ID";
}
private void Select()
{
try
{
conn.Open();
sql = #"select * from docen_selecionar()";
cmd = new NpgsqlCommand(sql, conn);
dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
dgvTabela.DataSource = null;
dgvTabela.DataSource = dt;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Error: " + ex.Message);
}
}
private void DgvTabela_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
txtName.Text = dgvTabela.Rows[e.RowIndex].Cells["_docente_id"].Value.ToString();
txtID.Text = dgvTabela.Rows[e.RowIndex].Cells["_nome_docente"].Value.ToString();
txtVAT.Text = dgvTabela.Rows[e.RowIndex].Cells["_nif_number"].Value.ToString();
txtDepart.Text = dgvTabela.Rows[e.RowIndex].Cells["_departamento"].Value.ToString();
txtDegree.Text = dgvTabela.Rows[e.RowIndex].Cells["_grau_academico"].Value.ToString();
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
rowIndex = -1;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Select();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher to update");
return;
}
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher ID to delete");
return;
}
try
{
conn.Open();
sql = #"select * from docen_apagar(:_docente_id)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
if ((int)cmd.ExecuteScalar() == 1)
{
MessageBox.Show("Teacher deleted successfully");
rowIndex = -1;
Select();
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Delete fail. Please try again. Error:" + ex.Message);
}
}
//save - esqueci-me de alterar o name
private void iconButton1_Click(object sender, EventArgs e)
{
int result = 0;
if (rowIndex < 0) //insert
{
try
{
conn.Open();
sql = #"select * from docen_registar(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Inserted new Teacher successfully");
Select();
}
else
{
MessageBox.Show("Inserted fail");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Inserted fail, please try again. Error: " + ex.Message);
}
}
else //update
{
try
{
conn.Open();
sql = #"select * from docen_update(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Successfully updated");
Select();
}
else
{
MessageBox.Show("Updated fail, please try again.");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Updated fail, please try again. Error: " + ex.Message);
}
}
result = 0;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = false;
}
}
}
I'm trying to create 4 buttons: insert, update, delete and save and when I click save it gives the following error:
"Error: 42601 syntax error at or near ":""
I Really don't know what it is.
Can someone help me?
When i use the code below,it does delete a row from a datagridview but when i refresh the page it does not..
private void DeleteData_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected)
{
dataGridView1.Rows.RemoveAt(row.Index);
break;
}
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow delrow = dataGridView1.Rows[i];
if (delrow.Selected == true)
{
dataGridView1.Rows.RemoveAt(i);
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + (i++) + "";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
What should i use to delete row from both local database and datagridview?
i think the connection not be assigned to the command object.
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
also i preferred to use DataGridView.SelectedRows instead of looping all records in grid.
full code
private void DeleteData_Click(object sender, EventArgs e)
{
var rowsToDelete = dataGridView1.SelectedRows;
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
sqcon.Open(); //ADDED
foreach (DataGridViewRow row in rowsToDelete)
{
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + row.Cells["Id"].Value.ToString() + "";
int count = Scmd.ExecuteNonQuery();
dataGridView1.Rows.Remove(row);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
sqcon.Close();
}
}
Try this,
Delete from database use the unique column or the Id column.
//Make datagridview cell[0] the unique column in your table.
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID='" + datagridview.rows[i].cell[0].value + "'";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have a group box contains radio buttons eg.
o Level 1
o Level 2
How can I load value from database and check radio botton on my GUI?
private void button_clone_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * from PPAPdatabase where [PSW ID]=" + txt_c_PSW_ID.Text + "";
OleDbDataReader dr = null;
dr = command.ExecuteReader();
while (dr.Read())
{
comboBox_PPAP.Text = (dr["Reason"].ToString());
checkedListBox_prodline.Text = (dr["Production Line"].ToString());
checkedListBox_owner.Text = (dr["Owner"].ToString());
txt_comment.Text = (dr["Comment"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.Message,
"Important Note",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
finally
{
connection.Close();
}
Thanks in advance!
Assuming your radio button is called radioButton1 and the column your referring to stores values as either 1 or 0 then you would do:
radioButton1.Checked = row["PPAP"].ToString() == "1";
I want to show all details of the member through the name selected in combo box..Im trying below given code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
con.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT FlatNo FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
tbOwnerName.Text = ((string)cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I understand that you need to get all column records from memberinfo table and display them in UI. For that, you need to use ExecuteReader instead of ExecuteScalar. I have implemented execute reader in below code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
using(SqlConnection connection = con )
{
connection.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT Top 1 Name,City FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
tbOwnerName.Text = dr["Name"].ToString();
tbOwnerCity.Text = dr["City"].ToString();
//similarly store other column values in respective text boxes or wherever you need to get it displayed.
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I have a problem in listview.I my listview i have five columns(question_number,question_text,start_time,end_time,status). the first four columns will be fetch the data from the database.once the data has entered i have to compare the starttime and with the current time.once the starttime is greater than current time then i have to update the status column as expired. otherwise i have to say not expired.
I have attached the code what i did so for.
I do no how to get the status updated in the status column.Please any one help me.thanks in advance.
public void GetData()
{
try
{
myConnection = new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish;Persist Security Info=True;Data Source=ENMEDIA-CCDDFE5\ENMEDIA");
//myConnection.Open();
//SqlDataReader dr = new SqlCommand("SELECT question_text,question_id FROM otvtbl_question ", myConnection).ExecuteReader();
// listView1.Columns.Clear();
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT question_id,question_text,start_time,end_time FROM otvtbl_question");
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = MyString1;
dr = cmd.ExecuteReader();
//Adding The Column Name From The DataBase
for (int i = 0; i < dr.FieldCount; i++)
{
ColumnHeader ch = new ColumnHeader();
ch.Text = dr.GetName(i);
//listView1.Columns.Add(ch);
}
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
for (int i = 1; i < dr.FieldCount; i++)
{
itmX.SubItems.Add(dr.GetValue(i).ToString());
}
listView1.Items.Add(itmX);
}
dr.Close();
myConnection.Close();
}
catch (Exception ex)
{
//Error Message While Fetching
MessageBox.Show("Error While Fetching the data From the DataBase" + ex);
}
finally
{
//Closing The Connection
if (dr != null)
dr.Close();
if (myConnection.State == ConnectionState.Open)
myConnection.Close();
}
Something like this?
while (dr.Read())
{
...
listView1.Items.Add(itmX);
if (dr.GetDateTime(2) > dr.GetDateTime(3))
{
itmX.SubItems.Add("Expired");
}
}