Overlapping in listview c# - 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.

Related

List append is overriding previous values with latest value

I have a checkbox where I am trying to add the datafield from rows which have been checked in gridview. Problem is the list is not populating all the values instead it overrides previous value with latest value.
public List<int> ModuleEnrollmentList = new List<int>();
protected void ChkSelected_CheckedChanged(object sender, EventArgs e)
{
ASPxCheckBox cbChkBox = sender as ASPxCheckBox;
GridViewDataItemTemplateContainer container = cbChkBox.NamingContainer as GridViewDataItemTemplateContainer;
string moduleEnrollmentId = string.Empty;
if (cbChkBox.Checked)
{
for (int i = 0; i < grvQualificationScheduleDetails.VisibleRowCount; i++)
{
moduleEnrollmentId = container.KeyValue.ToString();
AddModuleId(Convert.ToInt32(moduleEnrollmentId));
}
}
//AddModuleId(Convert.ToInt32(moduleEnrollmentId));
}
public void AddModuleId(int mdleEnrollId)
{
ModuleEnrollmentList.Add(mdleEnrollId);
}

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;
}

calendar column c# in datagridview

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

bind many dropdownlist in a continous fashion

Hi all i need to bind a list of dropdown to values in database.Each drop down will be inside a panel and i have named it as ddlxx1,ddlxx2,ddlxx3 in a continuous fashion. all these drop down list will have the same data source.Is there any way to bind these control in a loop or should i find control each time which is in panel then bind it?
Something like:
for(int i=1;i<=10;i++)
{
ddlxx+"i".DataSource = Prod.GetValues();
ddlxx+"i".DataTextField = "ComponentID";
ddlxx+"i".DataValueField = "ComponentName";
ddlxx+"i".DataBind();
}
Please help
If your drop down lists are added to the mark-up you can simply do the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
for(int i=1;i<=10;i++)
{
var ddl = FindControl("ddlxx" + i) as DropDownList;
if (ddl != null)
{
BindDropDown(ddl);
}
}
}
}
private void BindDropDown(DropDownDataList ddl)
{
ddl.DataSource = Prod.GetValues();
ddl.DataTextField = "ComponentID";
ddl.DataValueField = "ComponentName";
ddl.DataBind();
}
Try this:
for (int i = 1; i <= 10; i++)
{
DropDownList drp = (DropDownList)panel1.FindControl("ddlxx" + i.ToString());//panel1 is your panel which contain dropdown ddlxx1,ddlxx2,ddlxx3...
drp.DataSource = Prod.GetComponents();
drp.DataTextField = "ComponentID";
drp.DataValueField = "ComponentName";
drp.DataBind();
}

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