I have my code as follows:
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
actGrid.Columns.Add(chk);
chk.HeaderText = "Select";
chk.Name = "select";
chk.ReadOnly = false;
DataGridViewTextBoxColumn mc_no = new DataGridViewTextBoxColumn();
actGrid.Columns.Add(mc_no);
mc_no.HeaderText = "M/C Number";
mc_no.Name = "mc_no";
mc_no.Width = 200;
mc_no.ReadOnly = true;
DataGridViewTextBoxColumn act_name = new DataGridViewTextBoxColumn();
actGrid.Columns.Add(act_name);
act_name.HeaderText = "Name";
act_name.Name = "member";
act_name.Width = 262;
act_name.ReadOnly = true;
while (DR.Read())
{
actGrid.Rows.Add(true, DR.GetInt32(0).ToString(), DR.GetString(2) + " " + DR.GetString(1));
}
Which produces the following output:
And now I want to perform some actions based on which accounts were selected (by toggling the trailing checkboxes), especially M/C Number.
// iterate over DataGridView rows
foreach (DataGridViewRow row in actGrid.Rows)
{
// check, if row is selected by checkbox
if (Equals(row.Cells["select"].Value, true))
{
// get values for selected row
var mc_no_Value = (string)row.Cells["mc_no"].Value;
var member_Value = (string)row.Cells["member"].Value;
// do smth with values here
}
}
Related
I have a problem with a DataGridView, as you can see from down here, when I enter a value (LOL) within the cells is actually only it appears in the last line
Code:
private void CaricaNoteLavaggio()
{
using (DatabaseConnection db = new DatabaseConnection())
{
const string query = "" // My query
using (MySqlDataReader reader = db.ExecuteReader(query))
{
if (reader.HasRows)
{
while (reader.Read())
{
DataGridViewRow row = new DataGridViewRow();
dataGridNoteLavaggio.Rows.Add(row);
foreach (DataGridViewCell cell in dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells)
{
cell.Value = "LOL";
}
}
}
}
}
}
The columns of the DataGridView I create dynamically using this piece of code (if that can be useful)
DataGridViewTextBoxColumn txtId = new DataGridViewTextBoxColumn();
txtId.HeaderText = "ID";
txtId.Name = "id";
txtId.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
txtId.Visible = false;
dataGridNoteLavaggio.Columns.Add(txtId);
// Function that returns the list of languages (EN, FR, ES, etc. ...)
List<string> lingue = DatabaseFunctions.GetLingue();
foreach (var lingua in lingue)
{
DataGridViewTextBoxColumn txtDesc = new DataGridViewTextBoxColumn();
txtDesc.HeaderText = lingua;
txtDesc.Name = lingua;
txtDesc.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridNoteLavaggio.Columns.Add(txtDesc);
}
I tried it with debugging to follow the indices in the cycle are correct but despite the result is wrong.
Because you insert data in the new row and new row always added to last of all.
for change data from first row after adding row you must change this code:
dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells
to
dataGridNoteLavaggio.Rows[index].Cells
and index set from Rows.Add() method. and your codes should like this:
private void CaricaNoteLavaggio()
{
using (DatabaseConnection db = new DatabaseConnection())
{
const string query = "" // My query
using (MySqlDataReader reader = db.ExecuteReader(query))
{
if (reader.HasRows)
{
while (reader.Read())
{
DataGridViewRow row = new DataGridViewRow();
var index = dataGridNoteLavaggio.Rows.Add(row);
foreach (DataGridViewCell cell in dataGridNoteLavaggio.Rows[index].Cells)
{
cell.Value = "LOL";
}
}
}
}
}
}
I am trying to add a rows to a RadGridView when a use click a button on the form (ie. "Add".)
When the form load I add columns to the RadGridView and make all of them all ReadOnly except one .
When a user click the "Add" button, I want to add a row to this RadGridView. Basically, a user types a UPC code, then I read data from the database and add new row in a grid view with the item name, item price.
Here is what I did to create the columns
private void Register_Load(object sender, EventArgs e) {
GridViewTextBoxColumn UPC = new GridViewTextBoxColumn();
UPC.Name = "UPC";
UPC.HeaderText = "UPC";
UPC.FieldName = "UPC";
UPC.MaxLength = 50;
UPC.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(UPC);
radGridView1.Columns["UPC"].Width = 120;
radGridView1.Columns["UPC"].ReadOnly = true;
GridViewTextBoxColumn ItemName = new GridViewTextBoxColumn();
ItemName.Name = "Item Name";
ItemName.HeaderText = "Item Name";
ItemName.FieldName = "ItemName";
ItemName.MaxLength = 100;
ItemName.TextAlignment = ContentAlignment.BottomRight;
radGridView1.MasterTemplate.Columns.Add(ItemName);
radGridView1.Columns["Item Name"].Width = 210;
radGridView1.Columns["Item Name"].ReadOnly = true;
GridViewDecimalColumn QtyColumn = new GridViewDecimalColumn();
QtyColumn.Name = "Qty";
QtyColumn.HeaderText = "Quantity";
QtyColumn.FieldName = "Qty";
QtyColumn.DecimalPlaces = 1;
radGridView1.MasterTemplate.Columns.Add(QtyColumn);
radGridView1.Columns["Qty"].Width = 75;
GridViewMaskBoxColumn PriceColumn = new GridViewMaskBoxColumn();
PriceColumn.Name = "Unit Price";
PriceColumn.FieldName = "UnitPrice";
PriceColumn.HeaderText = "Unit Price";
PriceColumn.MaskType = MaskType.Numeric;
PriceColumn.Mask = "C";
PriceColumn.TextAlignment = ContentAlignment.BottomRight;
PriceColumn.FormatString = "{0:C}";
PriceColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(PriceColumn);
radGridView1.Columns["Unit Price"].Width = 75;
radGridView1.Columns["Unit Price"].ReadOnly = true;
GridViewMaskBoxColumn TotalColumn = new GridViewMaskBoxColumn();
TotalColumn.Name = "Total Price";
TotalColumn.FieldName = "TotalPrice";
TotalColumn.HeaderText = "Total Price";
TotalColumn.MaskType = MaskType.Numeric;
TotalColumn.Mask = "C";
TotalColumn.TextAlignment = ContentAlignment.BottomRight;
TotalColumn.FormatString = "{0:C}";
TotalColumn.DataType = typeof(decimal);
radGridView1.MasterTemplate.Columns.Add(TotalColumn);
radGridView1.Columns["Total Price"].Width = 75;
radGridView1.Columns["Total Price"].ReadOnly = true;
}
To add the row Here is what I am doing "when a user click the 'Add' button)
private void ButtonAdd_Click(object sender, EventArgs e) {
string UPC = InputUPC.Text.Trim();
if (UPC.Length < 3) {
return;
}
string sql = " SELECT p.productName, p.price "
+ " FROM products AS p "
+ " WHERE p.productUPC = #upc ";
var parms = new List<MySqlParameter>();
parms.Add(new MySqlParameter("#upc", UPC));
var db = new dbConnetion();
foreach (var i in db.getData(sql, parms, r =>
new ProductsTable() {
_productName = r["productName"].ToString(),
_price = Convert.ToDouble(r["price"])
}
)
) {
//radGridView1.Rows[0].Cells[0].Value = 4.3;
radGridView1.Rows[0].Cells["UPC"].Value = UPC;
radGridView1.Rows[0].Cells["Item Name"].Value = i._productName;
radGridView1.Rows[0].Cells["Qty"].Value = "1";
radGridView1.Rows[0].Cells["Unit Price"].Value = i._price;
radGridView1.Rows[0].Cells["Total Price"].Value = (Convert.ToDouble(i._price) * Convert.ToInt32(radGridView1.Rows[0].Cells["Qty"].Value)).ToString();
}
}
But the add row is giving me an error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How can I correctly add rows to the RadGridView when the "Add" button is clicked.
ButtonAdd_Click is wrong because the foreach is always trying to set row 0, which doesn't exist.
You don't specify what GridView you are using, so I can't give specifics, but typically you should be able to call Rows.Add(...).
I have to bind each cell of rows with different data like.
ProductID Color(DataGridviewComboBoxColumn)
1 Red - (ComboboxCell having value only Red,Black,Green and Red is Selected)
....
4 Yellow- (ComboboxCell having value only Yellow,Gold and Yellow is Selected)
When I bind Items of cell and debug it will show Items in DataGridviewComboBoxCell but when going to run application it will display blank on select Combobox.
What can i do for this?
Form Design
private void InitializeComponent()
{
this.dataGridView2 = new System.Windows.Forms.DataGridView();
this.ProductId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Color = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.ColorIds = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit();
this.SuspendLayout();
//
// dataGridView2
//
this.dataGridView2.AllowUserToAddRows = false;
this.dataGridView2.AllowUserToDeleteRows = false;
this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView2.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ProductId,
this.Color,
this.ColorIds});
this.dataGridView2.Location = new System.Drawing.Point(12, 12);
this.dataGridView2.Name = "dataGridView2";
this.dataGridView2.Size = new System.Drawing.Size(704, 312);
this.dataGridView2.TabIndex = 1;
//
// ProductId
//
this.ProductId.DataPropertyName = "ProductId";
this.ProductId.HeaderText = "ProductId";
this.ProductId.Name = "ProductId";
//
// Color
//
this.Color.HeaderText = "Color";
this.Color.Name = "Color";
this.Color.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.Color.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
// ColorIds
//
this.ColorIds.DataPropertyName = "ColorIds";
this.ColorIds.HeaderText = "ColorIds";
this.ColorIds.Name = "ColorIds";
this.ColorIds.Visible = false;
}
Code :
dataGridView2.AutoGenerateColumns = false;
DataTable dt = //data from Product Table
dataGridView2.DataSource = dt;
DataTable dtColors = //data from Color Table
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
String ColorIds = dataGridView2.Rows[i].Cells["ColorIds"].Value.ToString();
DataTable dtfiltered = dtColors.Select("ColorId IN (" + ColorIds + ")").CopyToDataTable();
DataGridViewComboBoxCell col = (DataGridViewComboBoxCell)dataGridView2.Rows[i].Cells["Color"];
col.Items.Clear();
foreach (DataRow dr in dtfiltered.Rows)
{
col.Items.Add(new ComboBoxItem(dr["ColorId"].ToString(), dr["Color"].ToString()));
}
col.Value = col.Items[0];
}
I have added button to datagrid view but when ever the function is called more than once then new button adds I need to stop this addition
void AddtoGrid()
{
try
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
table.Columns.Add("Action");
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
row["Action"] = bcol.Text;
table.Rows.Add(row);
}
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
catch (Exception ca)
{
MessageBox.Show(ca.ToString());
}
}//End Function for Getting Present Users
I'm not quite sure I understand your question, though I believe that you need to encapsulate creation of the new column into it's own method and only call it once - in the constructor for instance.
For example:
void CreateDeleteColumn()
{
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
UsersView.Columns.Add(bcol);
}
That should stop it adding a column every time you populate the list view.
Hope this helps and sorry if I misunderstood.
Tony
EXACT duplicate of Datagrid View Button
repeat
I have added button to datagrid view but when ever the function is called more than once then new button adds I need to stop this addition
void AddtoGrid()
{
try
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
table.Rows.Add(row);
}
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
catch (Exception ca)
{
MessageBox.Show(ca.ToString());
}
}//End Function for Getting Present Users
Split the method up in two:
1.) To setup the grid structure
2.) To add new rows
public void SetupDataGridView()
{
table = new DataTable();
bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Action ";
bcol.Text = "Delete";
bcol.Name = "deleteUserButton";
bcol.UseColumnTextForButtonValue = true;
table.Columns.Add("Name");
table.Columns.Add("Type");
table.Columns.Add("Status");
table.Columns.Add("Date Created");
UsersView.DataSource = table;
UsersView.AllowUserToAddRows = false;//To remove extra row at the end
UsersView.Columns.Add(bcol);
}
public void PopulateDataGridView()
{
for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
{
row = table.NewRow();
asc.Add(userAction.UserName[i]);
row["Name"] = userAction.UserName[i];
row["Type"] = userAction.UserType[i];
row["Status"] = userAction.UserStatus[i];
row["Date Created"] = userAction.DateCrea[i];
table.Rows.Add(row);
}
}
And this is still a suboptimal approach, but that's the most anyone can do for someone with your skills.
You lack basic knowledge of programming and object oriented programming in particular. Get a book (e.g. chris sells' book on windows forms programming) read it, and then come back. You will benefit from it!