calendar column c# in datagridview - c#

Basically I want to show a calendar when I edit some columns in my Datagridview.
Following How to: Host Controls in Windows Forms DataGridView Cells from MSDN I can add wanted kind of column at building.
But in my case, I have to use a datasource provided by an Excel reader which give headings have to be connected to date type columns.
private DataGridView AddCalendars(DataGridView dtgv)
{
dtgv.DataSource = controller.getEmptyDataTable(); // DataTable provided by excel reader
var l = dtgv.Columns.Count;
string[] dateColumns = {"date_received", "date_of_birth"};
for (var i = 0; i < l; ++i)
{
if ( dateColumns.Any( dtgv.Columns[i].HeaderText.Contains )
{
dtgv.Columns[i] = new CalendarColumn(); // this line does not work cause by readonly
}
}
return dtgv;
}
How can I apply Calendar Column control to selected columns ?
Or, how can I obtain same result by building Datagridview different way ?

find an acceptable solution working around this post http://www.codeproject.com/Questions/175124/placing-datetimepicker-in-datagridview
private DateTimePicker cellDateTimePicker;
private List<int> dateColumnsIndexes;
public MainForm()
{
InitializeComponent();
///
this.cellDateTimePicker = new DateTimePicker();
this.cellDateTimePicker.ValueChanged += new EventHandler(cellDateTimePickerValueChanged);
this.cellDateTimePicker.Visible = false;
this.cellDateTimePicker.CustomFormat = "dd/MM/yyyy";
this.cellDateTimePicker.Format = DateTimePickerFormat.Custom;
this.dataGridView1.Controls.Add(cellDateTimePicker);
(...)
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
var index = masterDataGridView.CurrentCell.ColumnIndex;
if (this.dateColumnsIndexes.Contains(index))
{
Rectangle tempRect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
cellDateTimePicker.Location = tempRect.Location;
cellDateTimePicker.Width = tempRect.Width;
try
{
cellDateTimePicker.Value = DateTime.Parse(dataGridView1.CurrentCell.Value.ToString());
}
catch
{
cellDateTimePicker.Value = DateTime.Now;
}
cellDateTimePicker.Visible = true;
}
}
void cellDateTimePickerValueChanged(object sender, EventArgs e)
{
masterDataGridView.CurrentCell.Value = cellDateTimePicker.Value.ToString("dd/MM/yyyy");
cellDateTimePicker.Visible = false;
}
private void AddCalendars(DataGridView dtgv)
{
dateColumnsIndexes = new List<int>();
dtgv.DataSource = controller.getEmptyDataTable(); // DataTable provided by excel reader
var l = dtgv.Columns.Count;
string[] dateColumns = {"date_received", "date_of_birth"};
for (var i = 0; i < l; ++i)
{
if ( dateColumns.Any( dtgv.Columns[i].HeaderText.Contains )
{
dateColumnsIndexes.add(i);
}
}
}

Related

How to bind dynamically created text box?

I'm trying to create pricelist for hotel. I'm having a list of dates, and list of room types in hotel. That lists can contain random number of elements. That is created dynamically, and here is the code:
private void CreateControls() { var colIndex = 0;
var vrsteSoba = _Presenter.VrstaSobeDto.ToArray();
foreach (var bindingItem in vrsteSoba)
{
var lbl = new Label()
{
Width = LABEL_WIDTH,
Height = LABEL_HEIGHT - 5,
Left = 10,
Top = 30 + colIndex * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL),
Text = bindingItem
};
_dataPanel.Controls.Add(lbl);
colIndex++;
}
int a = 1;
foreach (var date in _Presenter.CeneTarifa)
{
int y = 0;
var panel = new Panel
{
Height = PANEL_HEIGHT * (vrsteSoba.Length-4),
Width = EDIT_BOX_WIDTH,
Left = a * (EDIT_BOX_WIDTH + SPACE_BETWEEN_CONTROL + 50),
Top = 5
};
_dataPanel.Controls.Add(panel);
var label = new Label
{
Height = EDIT_BOX_HEIGHT,
Location = new Point(0, 10),
Text = date.Datum,
Margin = new Padding(0)
};
panel.Controls.Add(label);
int index = 0;
foreach (var item in date.VrstaSobeCena)
{
var box = new TextBox();
panel.Controls.Add(box);
box.Height = EDIT_BOX_HEIGHT;
box.Width = EDIT_BOX_WIDTH;
box.Location = new Point(0, 30 + y * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL));
box.DataBindings.Add(new Binding(nameof(box.Text), date, date.Cena[index].Cena1));
y++;
index++;
}
++a;
}
_dataPanel.AutoScroll = true;
}`
Here is image of that representation.
Now I'm facing a problem of data binding. I need to bind price, two way, for each text box. And I'm stuck.
I have tried to bind it to property name, but then all boxes get same value. If I try to bind it to value via index, I'm getting error
Cannot bind to the property or column 34 on the DataSource. Parameter name: dataMember
Code below is used to fill model that is used in presenter
` private void FillCenePoTarifi() { var sobeArr = VrstaSobeDto.ToArray();
foreach (var datum in Datumi)
{
var dictionary = new Dictionary<string, decimal>();
var cene = new List<Cena>();
foreach (var item in sobeArr)
{
var tarif = _Tarife.Where(x => x.SifTarife == item).FirstOrDefault();
if (tarif != null)
_SastavTarife = HotelierServerLocal.Default.TarifaViewBlo.GetSastaveTarife(tarif.IdTarife);
//proveriti ovu logiku
var cena = _SastavTarife.Where(x => x.Cena1 != 0).Select(c => c.Cena1).FirstOrDefault();
cene.Add(new Cena { Cena1 = cena.ToString()});
dictionary.Add(item, cena);
}
var model = new CenePoTarifi
{
Datum = datum,
VrstaSobeCena = dictionary,
Cena = cene
};
CeneTarifa.Add(model);
}
}`
Finally here are classes that use as model.
` public class CenePoTarifi{
public Dictionary<string, decimal> VrstaSobeCena { get; set; } = new Dictionary<string, decimal>();
public string Datum { get; set; }
private List<Cena> _Cena;
public List<Cena> Cena
{
get => _Cena;
set
{
_Cena = value;
NotifyPropertyChanged("Cena");
}
}
public class Cena :
{
private string _Cena1;
public string Cena1
{
get => _Cena1;
set
{
_Cena = value;
NotifyPropertyChanged("Cena1");
}
}
}`
Does anyone has any suggestions?
Your question is: How to bind dynamically created text box. Here is one tested way for accomplishing that specific task.
First create some textboxes dynamically:
public MainForm()
{
InitializeComponent();
buttonRandom.Click += (sender, e) => generateRandomList();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
List<TextBox> tmp = new List<TextBox>();
for (int column = 1; column < tableLayoutPanel.ColumnCount; column++)
{
for (int row = 1; row < tableLayoutPanel.RowCount; row++)
{
TextBox textBox = new TextBox { Anchor = (AnchorStyles)0xF };
tableLayoutPanel.Controls.Add(textBox, column, row);
tmp.Add(textBox);
textBox.KeyDown += onAnyTextBoxKeyDown;
}
}
_textboxes = tmp.ToArray();
// Generate first dataset
generateRandomList();
}
TextBox[] _textboxes = null;
Then, whenever a new random list is generated, clear any old text and databindings from every TextBox before creating a new data binding for it.
public static Random Rando { get; } = new Random(2);
private void generateRandomList()
{
// Clear ALL the data + bindings for ALL the textboxes.
foreach (var textbox in _textboxes)
{
textbox.Clear();
textbox.DataBindings.Clear();
}
// Generate and create new bindings
int count = Rando.Next(1, 79);
for (int i = 0; i < count; i++)
{
var textbox = _textboxes[i];
VrstaSobeCena vrstaSobeCena =
new VrstaSobeCena{ Sobe = (Sobe)tableLayoutPanel.GetRow(textbox) };
textbox.Tag = vrstaSobeCena;
textbox.DataBindings.Add(
new Binding(
nameof(TextBox.Text),
vrstaSobeCena,
nameof(VrstaSobeCena.Cena),
formattingEnabled: true,
dataSourceUpdateMode: DataSourceUpdateMode.OnPropertyChanged,
null,
"F2"
));
// TO DO
// ADD vrstaSobeCena HERE to the Dictionary<string, decimal> VrstaSobeCena
}
}
The classes shown in your code as binding sources may not bind correctly. One issue I noticed is that the property setters are failing to check whether the value has actually changed before firing the notification. Here's an example of doing that correctly. (For testing purposes I'm showing a Minimal Reproducible Sample "mock" version of a class that implements INotifyPropertyChanged.)
enum Sobe { APP4 = 1, APP5, STUDIO, SUP, APP6, STAND, STDNT, COMSTU, LUXSTU, APP4C, APP4L, APP62, APP6L }
class VrstaSobeCena : INotifyPropertyChanged
{
decimal _price = 100 + (50 * (decimal)Rando.NextDouble());
public decimal Cena
{
get => _price;
set
{
if (!Equals(_price, value))
{
_price = value;
OnPropertyChanged();
}
}
}
Sobe _sobe = 0;
public Sobe Sobe
{
get => _sobe;
set
{
if (!Equals(_sobe, value))
{
_sobe = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Finally, one way to test the two-way binding is to intercept the [Enter] key.
private void onAnyTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) && (sender is TextBox textbox))
{
e.SuppressKeyPress = e.Handled = true;
VrstaSobeCena vrstaSobeCena = (VrstaSobeCena)textbox.Tag;
string msg = $"Price for {vrstaSobeCena.Sobe} is {vrstaSobeCena.Cena.ToString("F2")}";
BeginInvoke((MethodInvoker)delegate {MessageBox.Show(msg); });
SelectNextControl(textbox, forward: true, tabStopOnly: true, nested: false, wrap: true);
}
}
Create a List for storing the textbox:
List<TextBox> lstTextbox = new List<TextBox>();
Create a class object that stores the values of "Date" and "room type"
public class RoomTypeDate
{
public string RoomType = "";
public string DateRange = "";
}
Immediately after you created the textbox, assigned the RoomTypeDate info to the tag, add it to lstTextbox.
foreach (var item in date.VrstaSobeCena)
{
var box = new TextBox();
panel.Controls.Add(box);
box.Height = EDIT_BOX_HEIGHT;
box.Width = EDIT_BOX_WIDTH;
box.Location = new Point(0, 30 + y * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL));
box.DataBindings.Add(new Binding(nameof(box.Text), date, date.Cena[index].Cena1));
// add the box to the list
lstTextbox.Add(box);
// mark the box with RoomType and DateRange
RoomTypeDate rtd = new RoomTypeDate();
rtd.RoomType = "APP4"; // get the room type
rtd.DateRange = "1.6 - 30.6"; // get date range
box.Tag = rtd;
y++;
index++;
}
Now, to get and set the room price:
public void SetRoomPrice(decimal price, string roomType, string dateRange)
{
foreach (var tb in lstTextBox)
{
var rtd = (RoomTypeDate)tb.Tag;
if(rtd.RoomType == roomType && rtd.DateRange == dateRange)
{
tb.Text = price.ToString();
return;
}
}
}
public decimal GetRoomPrice(string roomType, string dateRange)
{
foreach (var tb in lstTextBox)
{
var rtd = (RoomTypeDate)tb.Tag;
if(rtd.RoomType == roomType && rtd.DateRange == dateRange)
{
return Convert.ToDecimal(rt.Text);
}
}
return 0m;
}
*code untested, might contains bugs

Advanced item search in combobox C#

I wrote a program with C #
I have a combo box whose items are Binding from the database.I use AutoCompleteMode and AutoCompleteSource to search the combo box.But only when filtering does it find words whose first letter is the same as the input letter.While I need All items that contain these letters displayed.Is there a solution to this problem?
maybe this helps
// Example data
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
// Handle Text Box that you Fill
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.Tolower().Contains(comboBox1.Text.ToLower())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}

Winforms insert image into ListView / ImageList at index

Winforms, C#, VS2017
ImageList does not have an Insert method (however ListViewItemCollection does). I have tried a few different ways to insert a new image into the middle of a ListView and it's LargeImageList, but not getting it to work quite properly.
Anyone have any tried and true code that works properly?
This is what I have, but the images don't get synced properly to the items in the list.
protected void InsertThumbnail(string key, string keySelected)
{
var newImageList = new ImageList()
{
ImageSize = new Size(thumbWidth, thumbHeight)
};
var itemNew = new ListViewItem();
var foundSelected = false;
//lvAllPages.BeginUpdate();
for (int i = 0; i < lvAllPages.Items.Count; i++)
{
var item = lvAllPages.Items[i];
newImageList.Images.Add(item.Tag.ToString(), lvAllPages.LargeImageList.Images[i]);
if (item.Tag.ToString() == keySelected)
{
var image = batch.GetThumbnail(key);
newImageList.Images.Add(key, image);
itemNew = new ListViewItem()
{
BackColor = Color.Aquamarine,
ImageIndex = i,
Tag = key,
};
if (isLocal)
itemNew.Text = $"{GetFileName(key)} (insert) - {itemNew.ImageIndex}";
foundSelected = true;
}
if (foundSelected)
{
item.ImageIndex = item.ImageIndex + 1;
if (isLocal)
item.Text = $"{GetFileName(item.Tag.ToString())} - {item.ImageIndex}";
}
}
lvAllPages.LargeImageList.Dispose();
lvAllPages.LargeImageList = newImageList;
lvAllPages.Items.Insert(itemNew.ImageIndex, itemNew);
}
One more related thing, but not pertinent to the problems I am having. For anyone looking at this question and having similar issues, this helped with the issue of sorting items after inserting a new one. Default behavior when you insert a new ListViewItem at a given index, it will appear at the bottom of the list. I found this handy class to keep items sorted by index, which solved that problem:
class CompareByIndex : IComparer
{
private readonly ListView _listView;
public CompareByIndex(ListView listView)
{
this._listView = listView;
}
public int Compare(object x, object y)
{
int i = this._listView.Items.IndexOf((ListViewItem)x);
int j = this._listView.Items.IndexOf((ListViewItem)y);
return i - j;
}
}
And in the form load:
lvAllPages.ListViewItemSorter = new CompareByIndex(lvAllPages);
Obviously, that's a design decision. ImageList.Images is a ImageCollection and as such, it implements the IList interface.
Unfortunately, the Insert() method is allowed to throw a NotSupportedException. And that's what the list will do when used like a IList:
((IList)imageList.Images).Insert(5, new Bitmap(10,10));
System.NotSupportedException: 'Specified method is not supported.'
In order to have the images shown in a specific order, use the Add() method which takes the key:
imageList.Images.Add("1", new Bitmap(100,100));
That should also enable you to replace the image:
imageList.Images.RemoveByKey("1");
imageList.Images.Add("1", new Bitmap(200,200));
For that to work, you need to set the Sorting property:
listView1.Sorting = SortOrder.Ascending;
For storing additional information like path etc. use anotther data structure with the same key.
Here's the code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ImageList imageList = new ImageList();
Dictionary<string, Metadata> metadata = new Dictionary<string, Metadata>();
private string dir = #"H:\temp";
private void button1_Click(object sender, EventArgs e)
{
// You would set this in the designer, probably
listView1.Sorting = SortOrder.Ascending;
listView1.View = View.LargeIcon;
listView1.LargeImageList = imageList;
// Make sure we start from the beginning
listView1.Items.Clear();
imageList.Images.Clear();
metadata.Clear();
// Add items
for (int i = 0; i < 10; i++)
{
var filename = "1 ("+(i+1)+").png"; // Just strange names I have
var fullFileName = Path.Combine(dir, filename);
imageList.Images.Add(i.ToString(), Bitmap.FromFile(fullFileName));
metadata.Add(i.ToString(), new Metadata{Path = fullFileName});
listView1.Items.Add(i.ToString(), "Image " + i, i.ToString());
}
// Update view
listView1.Refresh();
listView1.Invalidate();
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 3; i < 6; i++)
{
var filename = "1 ("+(i+2)+").png";
var fullFileName = Path.Combine(dir, filename);
// Change image
imageList.Images.RemoveByKey(i.ToString());
imageList.Images.Add(i.ToString(), Bitmap.FromFile(fullFileName));
// Match metadata and image
metadata[i.ToString()] = new Metadata{Path = fullFileName};
}
listView1.Refresh();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
var key = listView1.SelectedItems[0].ImageKey;
label1.Text = metadata[key].Path;
}
else
{
label1.Text = "No image selected";
}
}
}
internal class Metadata
{
internal string Path;
}

Overlapping in listview c#

Good day, I have a list view that looks like this.
My problem is that the name of the items are overlapping, that name is from the database, do i have to set something in the properties for it not to overlap?
form_load code
private void FormAdhocReport_Load(object sender, EventArgs e)
{
LoadReport();
ToolBar(sRights);
}
LoadReport code:
private void LoadReport()
{
dsReports.Clear();
this.listReports.Items.Clear();
adhoc.AccountRowID = CurrentUserNameRowID;
string sRetXMLValue = adhoc.get_sp_Reports_View_Owner();
string XMLDOC = sRetXMLValue;
ReadXMLData(XMLDOC);
ListReportData();
//int count = listReports.Items.Count;
}
ListReportDataCode:
private void ListReportData()
{
try
{
// Get the table from the data set
DataTable dtable = dsReports.Tables[0];
// Clear the ListView control
this.listReports.Items.Clear();
// Display items in the ListView control
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
if (drow.RowState != DataRowState.Deleted)
{
// Define the list items
ListViewItem lvi = new ListViewItem(drow["ReportName"].ToString());
lvi.ImageIndex = 0;
lvi.SubItems.Add(drow["RowID"].ToString());
listReports.Items.Add(lvi);
}
}
}
catch { }
}
Don't mind this codes: string sRetXMLValue = adhoc.get_sp_Reports_View_Owner();
string XMLDOC = sRetXMLValue;
ReadXMLData(XMLDOC); because they're just for getting the data in the database.
Thanks in advance for your help.

Tag Array c# winforms

The code below lets me show emails received in a listview on when the selected index is changed displays the body of the selected email in a RTB. The problem is i changed the code to work with a data grid view and now the Tag part wont work
void SomeFunc() // This line added by Jon
{
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
ListViewItem itmp = new ListViewItem(email.From);
ListViewItem.ListViewSubItem itms1 =
new ListViewItem.ListViewSubItem(itmp, email.Subject);
ListViewItem.ListViewSubItem itms2 =
new ListViewItem.ListViewSubItem(itmp, email.FromName);
itmp.SubItems.Add(itms1);
itmp.SubItems.Add(itms2);
listView1.Items.Add(itmp).Tag = i;
richTextBox1.Text = email.Body;
}
// Save the email to an XML file
bundle.SaveXml("email.xml");
}
private void listView1_SelectionChanged(object sender, EventArgs e)
{
if (listView1.SelectedCells.Count > 0)
{
// bundle is now accessible in your event handler:
richTextBox1.Text = bundle.GetEmail((int)listView1.SelectedCells[0].Tag).Body;
}
}
Code for data grid view
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
string[] row = new string[] { email.From, email.Subject, email.FromName };
object[] rows = new object[] { row };
foreach (string[] rowArray in rows)
{
dataGridView1.Rows.Add(rowArray);
}
} // This line added by Jon
i have created earlier the code for datagrid view but you already done it so i haven't posted in your last question but i think , you should give a try to the below code.
// i am creating a new object here but , you can have a single object on the form
DataGridView dgv = new DataGridView();
private DataTable EmailSource { get; set; }
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.SelectionChanged+=new EventHandler(dgv_SelectionChanged);
Chilkat.MessageSet msgSet = imap.Search("ALL", true);
if (msgSet != null)
{
bundle = imap.FetchBundle(msgSet);
CreateDataTable();
if (bundle != null && dt!=null)
{
Chilkat.Email email;
int i;
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
if(email!=null)
{
DataRow drow = EmailSource.NewRow();
drow["Id"] = i.ToString();
drow["From"] = email.FromName;
drow["Subject"] = email.Subject;
drow["DateRecived"] = email.DateRecived;
// i am adding email body also
drow["Body"] =email.Body;
EmailSource.Rows.Add(drow);
}
}
// Save the email to an XML file
bundle.SaveXml("email.xml");
dgv.DataSource= EmailSource;
// Hiding Body from the grid
dgv.Columns["Body"].Visible =false;
}
}
// this event handler will show the last selected email.
void dgv_SelectionChanged(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection rows = dgv.SelectedRows;
if (rows != null)
{
// get the last selected row
DataRow drow = rows[rows.Count - 1].DataBoundItem as DataRow;
if (drow != null)
{
richTextBox1.Text = drow["Body"];
}
}
}
private void CreateDataTable()
{
EmailSource = new DataTable();
EmailSource.Columns.Add("Id");
EmailSource.Columns.Add("From");
EmailSource.Columns.Add("Subject");
EmailSource.Columns.Add("DateRecived");
EmailSource.Columns.Add("Body");
}
You are adding rows using listView1.Rows.Add(rowArray) in both the code listings. Is that a typo or you named the GridView like that.
Basically, you are storing the index of the email in the "Tag" property.
listView1.Items.Add(itmp).Tag = i;
You need to make sure that you do the same while adding items to the GridView too.
The DataGridView does not have an "Items" collection. To make it work, you need to bind the DataGridView to a collection of objects. Something like this should get you started:
List<Email> emails = new List<Email>();
for (i = 0; i < bundle.MessageCount; i++)
{
email = bundle.GetEmail(i);
emails.Add(email);
}
dataGridView.ItemsSource = emails;
You should not need to store the row index for each item in a "Tag" object - you can can get the selected index like this:
int selectedIndex = dataGridView.SelectedCells[0].RowIndex;

Categories