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(...).
Related
i had this unbound datagridview that add columns during form load;
here is the code;
private void loadfields()
{
dgvbulkentries.ColumnCount = 15;
dgvbulkentries.Columns[0].Name = "ID No";
dgvbulkentries.Columns[0].Width = 80;
dgvbulkentries.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[1].Name = "Surname";
dgvbulkentries.Columns[1].Width = 150;
dgvbulkentries.Columns[2].Name = "First Name";
dgvbulkentries.Columns[2].Width = 150;
dgvbulkentries.Columns[3].Name = "Name Extn";
dgvbulkentries.Columns[3].Width = 40;
dgvbulkentries.Columns[4].Name = "Middle Name";
dgvbulkentries.Columns[4].Width = 150;
dgvbulkentries.Columns[5].Name = "Course";
dgvbulkentries.Columns[5].Width = 110;
dgvbulkentries.Columns[6].Name = "Year";
dgvbulkentries.Columns[6].Width = 40;
dgvbulkentries.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[7].Name = "Street/Block";
dgvbulkentries.Columns[7].Width = 150;
dgvbulkentries.Columns[8].Name = "Subdivision";
dgvbulkentries.Columns[8].Width = 150;
dgvbulkentries.Columns[9].Name = "Barangay";
dgvbulkentries.Columns[9].Width = 150;
dgvbulkentries.Columns[10].Name = "Municipality/City";
dgvbulkentries.Columns[10].Width = 150;
dgvbulkentries.Columns[11].Name = "Province";
dgvbulkentries.Columns[11].Width = 150;
dgvbulkentries.Columns[12].Name = "GWA";
dgvbulkentries.Columns[12].Width = 60;
dgvbulkentries.Columns[12].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dgvbulkentries.Columns[13].Name = "Units";
dgvbulkentries.Columns[13].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgvbulkentries.Columns[13].Width = 50;
dgvbulkentries.Columns[14].Name = "Total School Fees";
dgvbulkentries.Columns[14].Width = 100;
dgvbulkentries.Columns[14].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewComboBoxColumn sexes = new DataGridViewComboBoxColumn();
sexes.HeaderText = "Sex";
sexes.Name = "Sex";
sexes.MaxDropDownItems = 4;
sexes.Items.Add("Male");
sexes.Items.Add("Female");
dgvbulkentries.Columns.Add(sexes);
dgvbulkentries.Columns[15].DisplayIndex = 5;
dgvbulkentries.Columns[15].Width = 80;
DataGridViewComboBoxColumn ssfapremarks = new DataGridViewComboBoxColumn();
ssfapremarks.HeaderText = "Remarks";
ssfapremarks.Name = "Remarks";
ssfapremarks.MaxDropDownItems = 4;
ssfapremarks.Items.Add("Enrolled");
ssfapremarks.Items.Add("Not Enrolled");
dgvbulkentries.Columns.Add(ssfapremarks);
dgvbulkentries.Columns[16].Width = 120;
}
I already set the code for currency textbox for a specific column in a datagridview. But the problem is, when i enter numbers in a cell, it does not change at all.
This is the code i included;
private void dgvbulkentries_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dgvbulkentries.Columns[14].DefaultCellStyle.Format = "n";
}
For example, when i enter numbers to a specific column in the datagridview, it does not format the value as currency format. i already did what you had suggested but its not working
what did i miss?
As mentioned in this answer
After knowing the issue I think using CellLeave event of data grid view will solve ur issue
void dataGridView1_CellLeave(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
dgvbulkentries.Columns[14].DefaultCellStyle.Format = "c2";
dgvbulkentries.Columns[14].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("en-GB");
dgvbulkentries.Columns[14].ValueType = typeof(decimal);
}
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
}
}
I'm calling a function from another class to a form to load datagridView. when i add only one dataGirdViewButtonColumn its works but when i add two the second one is not added.Another problem i have found is the button is added to empty row..
Function
public void LoadDataGridrcv(DataTable d, DataGridView dg)
{
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
DataGridViewButtonColumn btn1 = new DataGridViewButtonColumn();
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate()
{
dg.Rows.Clear();
dg.ColumnCount = 7;
dg.Columns[0].Name = "Order No.";
dg.Columns[0].Width = 110;
dg.Columns[1].Name = "Order Date";
dg.Columns[1].Width = 100;
dg.Columns[2].Name = "Excepted rcv date";
dg.Columns[2].Width = 100;
dg.Columns[3].Name = "Supplier";
dg.Columns[3].Width = 150;
dg.Columns[4].Name = "Total Items";
dg.Columns[4].Width = 80;
dg.Columns[5].Name = "Total";
dg.Columns[5].Width = 80;
dg.Columns[6].Name = "Status";
dg.Columns[6].Width = 100;
dg.Columns.Add(btn);
btn.HeaderText = "Click to view";
btn.Text = "View";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
btn1.HeaderText = "Click to recieve";
btn1.Text = "Recieve";
btn1.Name = "btn1";
btn1.UseColumnTextForButtonValue = true;
});
foreach (DataRow row in d.Rows)
{
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate() { dg.Rows.Add(row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString(), row[5].ToString(), row[6].ToString()); });
}
Thread.Sleep(100);
}
}
}
Usage
reatail r = new reatail();
t = new Thread(() => r.LoadDataGridrcv(r.loadAllOrder(), dataGridView1));
t.Start();
Hi i want to edit the selected item which is inserted in my listview. But i have a change tool in the menu. So i want the other Form (Form2) to appear when i press "change" in menu and the information in each textbox occur in its textbox (so I do not write it again because I only want to change something specific) and i can change the text depending on which textbox i want to change, as soon as i press "ok" button then the changes occur
Form1 = listview and the items
Form2 = the textboxes
Here is some code
Form1
private void MainForm_Load(object sender, EventArgs e)
{
ColumnHeader columnheader;
ListViewItem listviewitem;
listView1.LabelEdit = true;
// Ensure that the view is set to show details.
listView1.View = View.Details;
// Create seven column headers for sorting the data.
ColumnHeader header1, header2, header3, header4, header5, header6, header7, header8, header9, header10;
header1 = new ColumnHeader();
header2 = new ColumnHeader();
header3 = new ColumnHeader();
header4 = new ColumnHeader();
header5 = new ColumnHeader();
header6 = new ColumnHeader();
header7 = new ColumnHeader();
header8 = new ColumnHeader();
header9 = new ColumnHeader();
header10 = new ColumnHeader();
header1.Text = "ID";
this.listView1.Columns.Add(header1);
header1.Width = 50;
header2.Text = "First name";
this.listView1.Columns.Add(header2);
header2.Width = 110;
header3.Text = "Last name";
this.listView1.Columns.Add(header3);
header3.Width = 110;
header4.Text = "Home phone";
this.listView1.Columns.Add(header4);
header4.Width = 120;
header5.Text = "Cell phone";
this.listView1.Columns.Add(header5);
header5.Width = 110;
header6.Text = "Country";
this.listView1.Columns.Add(header6);
header6.Width = 110;
header7.Text = "Zip-code";
this.listView1.Columns.Add(header7);
header7.Width = 100;
header8.Text = "City";
this.listView1.Columns.Add(header8);
header8.Width = 110;
header9.Text = "Street";
this.listView1.Columns.Add(header9);
header9.Width = 110;
header10.Text = "Email";
this.listView1.Columns.Add(header10);
header10.Width = 150;
using(var customerframe = new CustomerFrame())
{
//if button OK is clicked then value will be inserted
if (customerframe.ShowDialog() == DialogResult.OK)
{
CustomerFiles.Contact contact = customerframe.GetContact();
CustomerFiles.Address address = customerframe.GetAddress();
CustomerFiles.Phone phone = customerframe.GetPhone();
CustomerFiles.Email email = customerframe.GetEmail();
//Items in my listview
listviewitem = new ListViewItem();
listviewitem.SubItems.Add(contact.FirstName);
listviewitem.SubItems.Add(contact.LastName);
listviewitem.SubItems.Add(phone.Home);
listviewitem.SubItems.Add(phone.Mobile);
listviewitem.SubItems.Add(address.Country);
listviewitem.SubItems.Add(address.ZipCode);
listviewitem.SubItems.Add(address.City);
listviewitem.SubItems.Add(address.Street);
listviewitem.SubItems.Add(email.Personal);
this.listView1.Items.Add(listviewitem);
}
}
}
Form2
internal CustomerFiles.Contact GetContact()
{
CustomerFiles.Contact contact = new CustomerFiles.Contact();
contact.FirstName = tbFirstName.Text;
contact.LastName = tbLastName.Text;
return contact;
}
internal CustomerFiles.Address GetAddress()
{
address.City = tbCity.Text;
address.Street = tbStreet.Text;
address.ZipCode = tbZipCode.Text;
address.country = cbCountry.Text;
return address;
}
internal CustomerFiles.Phone GetPhone()
{
CustomerFiles.Phone phone = new CustomerFiles.Phone();
phone.Home = tbHomePhone.Text;
phone.Mobile = tbCellPhone.Text;
return phone;
}
internal CustomerFiles.Email GetEmail()
{
CustomerFiles.Email email = new CustomerFiles.Email();
email.Personal = tbEmail.Text;
return email;
}
I really think you need something like a dataGridView but with list appearance, don't u?
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];
}