FORM IMAGE
I have two tables in my database
datatable
kar
datatable have two columns Product, Producttype. kar table also have two columns type, tax.
In my form I have a Datagridview with 3 columns Productname, type, tax.
Productname column is datagridviewcomboboxcolumn which display all the product from datatable. `
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
this.datatableTableAdapter.Fill(this.myBillDataSet.datatable);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
string item = null;
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True");
ComboBox cb = (ComboBox)sender;
item = cb.Text;
if (item != null)
{
SqlCommand cmd = new SqlCommand("select Producttype from datatable where product=#pro", con);
cmd.Parameters.AddWithValue("#pro", item);
con.Open();
string val = cmd.ExecuteScalar().ToString();
con.Close();
SqlCommand cmd2 = new SqlCommand("select tax from kar where type=#pro2", con);
cmd2.Parameters.AddWithValue("#pro2", val);
con.Open();
string val2 = cmd2.ExecuteScalar().ToString();
con.Close();
}
}
when user select any product from dropdown the type and tax column will display the value. I am getting the values but not able to display in gridview cell
You can directly insert value in your cells inside ComboBox_SelectedIndexChanged event using column index
dataGridView1.Rows[e.RowIndex].Cells[YourCellindex] = val;
dataGridView1.Rows[e.RowIndex].Cells[YourSecondCellindex] = val2;
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();
Hope It helps
Related
I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}
When I check a checkbox in dataGridView, the checkbox that I've checked is automatically becoming false because I am refreshing my dataGridView every second. What I want to happen is to cancel the refreshing every second when a dataGridView checkbox is checked.
Here is my code:
private void UpdateVisitors_Load(object sender, EventArgs e)
{
//Realtime refresh
refresher.Interval = (1 * 1000); // 10 secs
refresher.Tick += new EventHandler(refresh);
refresher.Start();
}
private void refresh(object sender, EventArgs e)
{
refreshLocal();
}
UPDATE
Here is my refreshLocal code that I've been using to refresh my dataGridView
void refreshLocal()
{
dgvLocal.Rows.Clear();
connection.Close();
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Select * from tbl_Registration ORDER BY [ID] DESC;";
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
myID = dr["ID"].ToString();
category = dr["Category"].ToString();
repname = dr["Representative"].ToString();
if (dr["City/Province"].ToString() == "")
{
city = dr["Province"].ToString();
}
else
{
city = dr["City/Province"].ToString();
}
pax = dr["Pax"].ToString();
male = dr["Male"].ToString();
female = dr["Female"].ToString();
students = dr["Students"].ToString();
ar = dr["AR Users"].ToString();
date = dr["Date & Time Added"].ToString();
dgvLocal.Rows.Add(false, myID, category, repname, city, pax,students, ar, date);
}
connection.Close();
}
You need to bind to the event CellValueChanged of your DataGridView and inside the handler, stop your timer depending on the value of your checkbox.
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (dataGridView.Columns[e.ColumnIndex].Name == "MyCheckBoxCellName" && dataGridView.Columns[e.ColumnIndex].Value) {
// Disable your Timer
refresher.Enabled = false;
}
}
I have a repeater and I used label for display and a hidden text box which holds the same value. Now I want to enable the text box so that the user can edit inputs in the table/repeater. Can anyone help me? below is my code
public void FillTable()
{
DataTable table = new DataTable();
using (MySqlConnection conn = Functions.GetConnection())
{
string sql = "SELECT FirstName, LastName from tbluser LIMIT 15";
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(table);
conn.Close();
}
}
asd.DataSource = table;
asd.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
asd.Visible = true;
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
Literal lblname = (Literal)item.FindControl("Label2");
TextBox txtbox = (TextBox)item.FindControl("Label3");
if (e.CommandName == "EDIT")
{
lblname.Visible = false;
txtbox.Visible = true;
You are not getting the textbox but the label twice:
TextBox txtbox = (TextBox)item.FindControl("Label3");
I have 5 datagridviews and I want to get details from the selected datagridview.
Like when selecting the gridview row, I want to take that row details with the gridview name.
private void assigncontrctbtn_Click(object sender, EventArgs e)
{
SqlConnection conn;
conn = ConnectionManager.GetConnection();
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
conn.Open();
string hh = "SELECT contractstatus from dbo.contracts where "here i need gridview name";
SqlCommand cmd = new SqlCommand(hh, conn);
string dd = Convert.ToString(cmd.ExecuteScalar());
if ((dd == "Contract logged") && (cmbCategory.Text != "Calculate Contract") && (cmbCategory.Text == "Verify Contract"))
{
MessageBox.Show("no");
}
else if ((dd == "Calculate Contract") && (cmbCategory.Text != "Verify Contract") && (cmbCategory.Text == "Calculate Contract"))
{
MessageBox.Show("verify");
}
else
{
if (dba.logcontract(cntrctnmecmb.Text, Convert.ToInt32(prcecodecmb.Text), seasoncmb.Text, cmplexitycmb.Text, revisecmb.Text, logdatetime, condatefrm.Value.Date.ToString("MM/dd/yyyy"), condteto.Value.Date.ToString("MM/dd/yyyy"), vatcmb.Text, statuscmb.Text, lstcmnt.Text, apprvedbycmb.Text, cmbCategory.Text))
{
MessageBox.Show("Successfully Added");
FillGridCal();
FillGridVer();
}
else
{
MessageBox.Show("Error occured");
}
}
}
You can have an an event say CellClick for each of your DataGridView. When a row is clicked, you can get the details that you want. I'm assuming that what you mean by take that row details is take the cell values for the selected row.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
string firstColumn = (string)dataGridView1.Rows[e.RowIndex].Cells[firstColumn.Name].Value;//I'm getting 1 column from the selected row, you can do a loop if you want to get all cells
string dataGridView = dgv.Name;//This is the DataGridView name
}
I have a question and I don't seem to get it right in this one... What I've been trying to do is enter a value (id) on a datagridview cell, pressing enter, and filling the adjacents cells with data from the DB (SQL), that matches the id that I entered in the first cell. The questions are:
How do I get the pressed key event on a datagridview?
How do I get the value from that particular cell into, let's an integer?
How do I add up rows from a datatable, without getting the first row deleted in the datagridview? Is there an update method to it?
Sorry if these are basic questions, but I don't seem to find an answer.
Thanks!
Edit: Here's the code I've been trying... what I accomplished with this is that when I press enter, I get a set of new empty columns on the datagrid aside of the columns that I already created
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[0];
if (cell.Value == null || cell.Value.Equals("") || cell.ColumnIndex == 0)
{
dataGridView1.CurrentRow.cell[0].FormattedValue as int;
int idArticle = Convert.ToInt32(row.Cells[0].Value);
//int idArticle = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
dataGridView1.AutoGenerateColumns = true;
string constring = #"Data Source=DAN;Initial Catalog=administration;Integrated Security=True ";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT id_article, article, quantity, precio FROM articlesSG WHERE id_article=#id_article", con))
{
cmd.Parameters.AddWithValue("id_article", idArticle);
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
}
}
}
To capture keys try this:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var tb =(DataGridViewTextBoxEditingControl)e.Control;
tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}
private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
}
To get the current value :
dataGridView1.CurrentRow.Cell[indexorname].FormattedValue as int
To add up rows use DataTable.Merge: