Edit listview items - c#

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?

Related

ListView items don't appear in the right column

I am trying to create a ListView programmatically and fill it with a list of data that is determined previously from a file. I am trying to set up the column headers and populate the data with the following code but the result is that the data is misaligned by one column as can be seen in the attached image. How can I make it so that the data aligned in the correct columns?
ListView listView1 = new ListView();
ColumnHeader logCountHeader = new ColumnHeader();
logCountHeader.Text = "#";
logCountHeader.Width = 40;[![enter image description here][1]][1]
listView1.Columns.Add(logCountHeader);
ColumnHeader logTypeHeader = new ColumnHeader();
logTypeHeader.Text = "Log Type";
logTypeHeader.Width = 150;
listView1.Columns.Add(logTypeHeader);
ColumnHeader dataHeader = new ColumnHeader();
dataHeader.Text = "Message";
dataHeader.Width = 300;
listView1.Columns.Add(dataHeader);
ColumnHeader timeHeader = new ColumnHeader();
timeHeader.Text = "Time";
timeHeader.Width = 150;
listView1.Columns.Add(timeHeader);
string log_type_name = "";
string log_data = "";
string log_date = "";
string log_number = "";
for (int i = (_debug_entries-1); i >= 0; i--)
{
log_number = i.ToString();
log_type_name = _log_type[i].ToString();
log_data = _log_data[i];
log_date = _log_timestamp[i].ToString();
ListViewItem listviewitem = new ListViewItem();
listviewitem.SubItems.Add(log_number);
listviewitem.SubItems.Add(log_type_name);
listviewitem.SubItems.Add(log_data);
listviewitem.SubItems.Add(log_date);
listView1.Items.Add(listviewitem);
}
return listView1;
The item string should be part of the ListView constructor, it is not a sub item.
ListViewItem listviewitem = new ListViewItem(log_number);
listviewitem.SubItems.Add(log_type_name);
listviewitem.SubItems.Add(log_data);
listviewitem.SubItems.Add(log_date);
listView1.Items.Add(listviewitem);
And you need to set the ListView.View to see the subitems
ListView listView1 = new ListView();
listView1.View = View.Details;
for (int i =0; i <= _debug_entries-1; i++){
log_number = i.ToString();
log_type_name = _log_type[i].ToString();
log_data = _log_data[i];
log_date = _log_timestamp[i].ToString();
ListViewItem listviewitem = new ListViewItem();
listviewitem.SubItems.Add(log_number);
listviewitem.SubItems.Add(log_type_name);
listviewitem.SubItems.Add(log_data);
listviewitem.SubItems.Add(log_date);
listView1.Items.Add(listviewitem);
}
Use above code it will solve your problem.

Windows Forms: Extra columns in DataGridView

My DataGridView is showing extra columns. The application is a windows forms application. What could I be doing wrong?
public ConvertisForm1()
{
InitializeComponent();
openFileDialog.Filter = "Files| *.chm;*.htm;*.html;*.rtf;*.xls;*.xlsx;*.xps;*.doc;*.docx";
dataGridView.AutoGenerateColumns = false;
dataGridView.RowHeadersVisible = false;
dataGridView.ColumnCount = 5;
dataGridView.RowCount = 20;
//delete button
var deleteDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = deleteDataGridViewButtonColumnName,
Text = "X",
Width =20
};
dataGridView.Columns.Insert(DeleteColumnIndex, deleteDataGridViewButtonColumn);
dataGridView.Columns[FileNameAndPathColumnIndex].Width=250;
dataGridView.Columns[FileNameAndPathColumnIndex].HeaderText = "File Path";
//browse button
var browseDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = browseDataGridViewButtonColumnName,
Text = "...",
Width = 30
};
dataGridView.Columns.Insert(BrowseButtonColumnIndex, browseDataGridViewButtonColumn);
//convert to dropdown
var convertToDataGridViewComboBoxColumn = new DataGridViewComboBoxColumn
{
HeaderText = "Convert to",
Name = convertToDataGridViewComboBoxColumnName,
DataSource = new ArrayList { convertToComboBoxDefault, "pdf", "word"},
Width = 100,
DefaultCellStyle =
{
NullValue = convertToComboBoxDefault,
DataSourceNullValue = convertToComboBoxDefault
}
};
dataGridView.Columns.Insert(ConvertToFileTypeColumnIndex, convertToDataGridViewComboBoxColumn);
var convertDataGridViewButtonColumn = new DataGridViewButtonColumn
{
HeaderText = "",
Name = convertDataGridViewButtonColumnName,
Text = "Convert",
Width = 50
};
dataGridView.Columns.Insert(ConvertButtonColumnIndex, convertDataGridViewButtonColumn);
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
#endregion
}
have you tried DataGridView1.AutoGenerateColumns = false; ?
or you can clear all Columns before adding new Columns
see link for reference: https://stackoverflow.com/a/7430993/5694113

Not able to add multiple DataGridViewButtonColumn at runtime

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

C# Displaying text box (present in the list view) value in a message box (wpf)

I have a list view in which each row contains 5 entries. The list box looks like this:
I need to store (display) the name of variable and the value present in "Physical value" column text box when i press OK button. For e.g. if i enter 45 in the physical value text box (only one row at a time) then the name of the variable and value "45" should be stored (displayed). I am able to retrieve the name of the variables but not the value of the text box.
My try:
This code will populate the list view with variables and bind it to the properties.
public void Populatevariables(IList<string> variables)
{
int rowcount = 0;
dataGrid.RowDefinitions.Clear();
dataGrid.ColumnDefinitions.Clear();
RowDefinition rd = new RowDefinition();
rd.Height = new GridLength();
dataGrid.RowDefinitions.Add(rd);
dataGrid.RowDefinitions.Add(new RowDefinition());
dataGrid.ColumnDefinitions.Add(new ColumnDefinition());
Label t1 = new Label();
t1.Content = "Variables";
Grid.SetColumn(t1, 0);
Grid.SetRow(t1, rowcount);
dataGrid.Children.Add(t1);
ListView VrblPopulateList = new ListView();
GridView g1 = new GridView();
g1.AllowsColumnReorder = true;
//l1.View = g1;
GridViewColumn g2 = new GridViewColumn();
g2.Header = "Name";
g2.Width = 200;
g2.DisplayMemberBinding = new Binding("Name");
g1.Columns.Add(g2);
GridViewColumn g5 = new GridViewColumn();
g5.Header = "DataType";
g5.Width = 200;
g5.DisplayMemberBinding = new Binding("DataType");
g1.Columns.Add(g5);
GridViewColumn g3 = new GridViewColumn();
g3.Header = "Current Value";
g3.Width = 200;
DataTemplate dt1 = new DataTemplate();
FrameworkElementFactory FF1 = new FrameworkElementFactory(typeof(TextBox));
FF1.SetBinding(TextBox.BindingGroupProperty, new Binding("Current_Value"));
FF1.SetValue(FrameworkElement.HeightProperty, Height = 30);
FF1.SetValue(FrameworkElement.WidthProperty, Width = 150);
dt1.VisualTree = FF1;
g3.CellTemplate = dt1;
g1.Columns.Add(g3);
GridViewColumn g6 = new GridViewColumn();
g6.Header = "Physical Value";
g6.Width = 200;
DataTemplate dt2 = new DataTemplate();
FrameworkElementFactory FF2 = new FrameworkElementFactory(typeof(TextBox));
FF2.SetBinding(TextBox.BindingGroupProperty, new Binding("Physical_Value"));
//FF2.AddHandler(TextBox.TextChangedEvent, txtchanged, true);
FF2.SetValue(FrameworkElement.HeightProperty, Height = 30);
FF2.SetValue(FrameworkElement.WidthProperty, Width = 150);
dt2.VisualTree = FF2;
g6.CellTemplate = dt2;
g1.Columns.Add(g6);
GridViewColumn g4 = new GridViewColumn();
g4.Header = "Action";
g4.Width = 200;
DataTemplate dt = new DataTemplate();
FrameworkElementFactory FF = new FrameworkElementFactory(typeof(Button));
FF.SetBinding(Button.BindingGroupProperty, new Binding("ToDo"));
FF.SetValue(FrameworkElement.HeightProperty,Height = 30);
FF.SetValue(FrameworkElement.WidthProperty, Width = 150);
FF.SetValue(System.Windows.Controls.Button.ContentProperty,"OK");
FF.AddHandler(Button.ClickEvent, new RoutedEventHandler(b1_click));
dt.VisualTree = FF;
g4.CellTemplate = dt;
g1.Columns.Add(g4);
VrblPopulateList.View = g1;
Grid.SetRow(VrblPopulateList, rowcount + 1);
dataGrid.Children.Add(VrblPopulateList);
for (int i = 0; i < variables.Count; i++)
{
Label lb1 = new Label();
lb1.Content = variables[i].Name;
Label lb2 = new Label();
lb2.Name = variables[i].datatype;
DataTemplate dd = new DataTemplate();
TextBox tb = new TextBox();
tb.Name = "TextBox" + i.ToString();
Button b1 = new Button();
VrblPopulateList.Items.Add(new User() { Name = lb1.Content, DataType = lb2.Name, Current_Value = tb, Physical_Value = tb, ToDo = b1 });
}
}
This code defines the property which is bind while populating:
public class User
{
public object Name { get; set; }
public string DataType { get; set; }
public Control Current_Value
{
get;
set;
}
public Control Physical_Value
{
get;
set;
}
public Control ToDo { get; set; }
}
At last this code will retrieve all the items when button is clicked.
private void b1_click(object sender, RoutedEventArgs e)
{
User item = (User)((Button)sender).DataContext;
TextBox t = (TextBox)item.Physical_Value;
MessageBox.Show(item.Name.ToString() + t.Text);
}
The text box value is always empty. I know it can be solved by adding handler to "text changed" event while populating. But i dont know how to do it. Please help.
As mentioned in the comment by #Ponas Justas i have to do following changes in my code:
Set the UpdateSourceTrigger property of the text box.
Change the user model accordingly.
After doing above changes my code looks like:
FF2.SetBinding(TextBox.BindingGroupProperty, new Binding("Physical_Value"));
FF2.SetBinding(TextBox.TextProperty, new Binding("PhysicalValueTxtChanged") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
User Model
public class User
{
public object Name { get; set; }
public string DataType { get; set; }
public Control Current_Value
{
get;
set;
}
public string _PhysicalValueTxtChanged = null;
public string PhysicalValueTxtChanged
{
get { return _PhysicalValueTxtChanged; }
set
{
_PhysicalValueTxtChanged = value;
}
}
public Control ToDo { get; set; }
}
After doing that the text in the text box can be easily stored by just modifying like this:
private void b1_click(object sender, RoutedEventArgs e)
{
User item = (User)((Button)sender).DataContext;
string txt = item.PhysicalValueTxtChanged;
MessageBox.Show(item.Name.ToString() + txt);
}
Thanks a lot Ponas Justas.

How to add rows to a RadGridView in WinForms using c#

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(...).

Categories

Resources