I'm currently trying to fill a TableLayoutPanel through a method which goes as follows:
private int _rowCount;
public void InitPaths()
{
int c = 1;
int a = 1;
while (a < _PathRows.Length - 1)
{
var label = new Label();
//
// Label - Format.
//
label.Dock = DockStyle.Fill;
label.AutoSize = false;
label.Text = _pfadZeilen[a];
label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
label.Size = new System.Drawing.Size(22, 13);
label.BackColor = System.Drawing.Color.Transparent;
TableLayoutP.Controls.Add(label, 3, c);
//Checkboxen Einfügen
var cbox = new CheckBox();
//
//Checkbox Format.
cbox.Anchor = System.Windows.Forms.AnchorStyles.None;
cbox.AutoSize = true;
cbox.CheckAlign = System.Drawing.ContentAlignment.MiddleCenter;
cbox.Name = "checkBoxPfad" + a;
cbox.Size = new System.Drawing.Size(15, 14);
cbox.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cbox.UseVisualStyleBackColor = true;
TableLayoutP.Controls.Add(cbox, 0, c);
a++;
c++;
}
this._rowCount = BibTable.GetRowHeights().Length; // which seems to be Holding the value only within the method
}
and then delete all rows on Action, through the following Method:
public void RemoveRows()
{
for (int row = _rowCount; row >= 0; row--)
{
BibTable.RowStyles.RemoveAt(row);
BibTable.RowCount--;
}
}
Now the Problem is, if I try to do anything with the TableLayoutP outside of the method where all rows are initialized, it will tell me:
Object reference not set to the instance of an object.
What can I do? Is there a way to get a method inside a method (I'm realising just how stupid that sounds while typing it) or any other way to deal with this Situation?
You are ittering through GetRowHeights(), returning the height of each row. But you are deleting from the RowStyles collection which is not directly related to the first collection. I assume that GetRowHeights() returns much more rows, than RowStyles has.
Why not:
BibTable.RowCount = 0;
BibTable.RowStyles.Clear();
You are ittering through GetRowHeights(), returning the height of each row. But you are deleting from the RowStyles collection which is not directly related to the first collection. I assume that GetRowHeights() returns much more rows, than RowStyles has.
Why not:
BibTable.RowCount = 0;
BibTable.RowStyles.Clear();
Related
From the below code, I dynamically create a list of buttons based on client names provided by a TCP connection from the clientNames[i] list.
private void updateClientListUI()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.updateClientListUI));
}
else
{
//Debug.WriteLine(clientNames[0]);
int basex = subPanelClient.Location.X;
int basey = subPanelClient.Location.Y;
for (int i = 0; i < clientNames.Count; i++)
{
Button b = new Button();
b.Left = basex;
b.Top = basey;
b.Size = new Size(25, 25); // <== add this line
b.Dock = DockStyle.Top;
b.ForeColor= Color.Gainsboro;
b.FlatStyle= FlatStyle.Flat;
b.FlatAppearance.BorderSize = 0;
b.Padding= new Padding(35, 0, 0, 0);
b.TextAlign = ContentAlignment.MiddleLeft;
basey += 25;
b.Name = clientNames[i];
b.Text = clientNames[i];
subPanelClient.Controls.Add(b);
buttonsAdded.Insert(i, b);
}
}
}
What I am trying to figure out, is how to delete a button (i). What I attempted is the following:
private void removingButtons(int i)
{
if (buttonsAdded.Count > 0)
{
Button buttonToRemove = buttonsAdded[i];
subPanelClient.Controls.Remove(buttonToRemove);
buttonsAdded.Remove(buttonToRemove);
}
}
Or if anyone would know how to update the current list of buttons from updateClientListUI() to the current latest list from clientNames[i] instead of a list being added onto another list.
The issue that Im getting is that obviously every time there is a connection or disconnection the list just keeps getting added instead of refreshing to the current list.
One way to do it would be to clear the old buttons on each update.
foreach (Button b in buttonsAdded)
{
subPanelClient.Controls.Add(b);
}
buttonsAdded.Clear();
for (int i = 0; i < clientNames.Count; i++)
{
Button b = new Button();
...
...
If the subPanelClient only contains those buttons, you could just use
subPanelClient.Controls.Clear();
Last remark: Your removingButtonk function seems to use this.Controls.Remove instead of subPanelClient.Controls.Remove.
I am in need of some assistance or advice/experience of someone else.
Here is what I'm struggling with:
In my project an objectlistview olvDifference is used to visualize items (Type Conflict) of a list. So far I was able to add the Columns needed and format them properly. But the format provided with
private void ConflictFormatRow(object sender,
BrightIdeasSoftware.FormatRowEventArgs e)
{
Conflict conflict = (Conflict)e.Model;
if (conflict == null) return;
if (conflict.resolution == ConflictResolution.None) e.Item.BackColor = conflictColor;
else if (conflict.resolution == ConflictResolution.UseMine) e.Item.BackColor = mineColor;
else if (conflict.resolution == ConflictResolution.UseTheirs) e.Item.BackColor = theirsColor;
else e.Item.BackColor = System.Drawing.Color.White;
if(e.Model == olvConflictList.SelectedObject)
{
BrightIdeasSoftware.RowBorderDecoration a = new BrightIdeasSoftware.RowBorderDecoration();
a.BorderPen.Color = Color.Black;
a.BorderPen.Width = 3;
a.CornerRounding = 0;
a.FillBrush = Brushes.Transparent;
e.Item.Decoration = a;
}
else
{
BrightIdeasSoftware.RowBorderDecoration b = new BrightIdeasSoftware.RowBorderDecoration();
b.BorderPen.Color = Color.Transparent;
b.BorderPen.Width = 0;
b.CornerRounding = 0;
b.FillBrush = Brushes.Transparent;
e.Item.Decoration = b;
}
}
In the constructor of the form (WFA), the AspectGetter is assigned and the objects to display are set.
Designer-Generated code equals the block below:
//
// olvConflictList
//
this.olvConflictList.AllColumns.Add(this.olvcConflictList);
this.olvConflictList.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.olvConflictList.CellEditUseWholeCell = false;
this.olvConflictList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvcConflictList});
this.olvConflictList.Cursor = System.Windows.Forms.Cursors.Default;
this.olvConflictList.FullRowSelect = true;
this.olvConflictList.Location = new System.Drawing.Point(780, 90);
this.olvConflictList.Name = "olvConflictList";
this.olvConflictList.Size = new System.Drawing.Size(286, 489);
this.olvConflictList.TabIndex = 18;
this.olvConflictList.UseCellFormatEvents = true;
this.olvConflictList.UseCompatibleStateImageBehavior = false;
this.olvConflictList.View = System.Windows.Forms.View.Details;
this.olvConflictList.FormatRow += new System.EventHandler<BrightIdeasSoftware.FormatRowEventArgs>(this.ConflictFormatRow);
this.olvConflictList.SelectedIndexChanged += new System.EventHandler(this.olvDifferenceGroups_SelectedIndexChanged);
//
// olvcConflictList
//
this.olvcConflictList.AspectName = "";
this.olvcConflictList.AutoCompleteEditor = false;
this.olvcConflictList.AutoCompleteEditorMode = System.Windows.Forms.AutoCompleteMode.None;
this.olvcConflictList.FillsFreeSpace = true;
this.olvcConflictList.Groupable = false;
this.olvcConflictList.HeaderCheckBoxUpdatesRowCheckBoxes = false;
this.olvcConflictList.Hideable = false;
this.olvcConflictList.IsEditable = false;
this.olvcConflictList.MinimumWidth = 50;
this.olvcConflictList.Searchable = false;
this.olvcConflictList.Sortable = false;
this.olvcConflictList.Text = "Conflicts";
this.olvcConflictList.UseFiltering = false;
this.olvcConflictList.Width = 283;
The only item in the olv has no BackGroundColor (White, default):
After starting the process, it is shown as one can see in the pic above, but I'd expect it to be initialized as in the pic below (after I hovered over it with my mouse the first time).
The only item in the olv has BackGroundColor conflictColor as assigned in the ConflictFormatRow:
Where do I need to improve my code? Any advices?
Well, I could figure it out myself.
I took a look at the source of OLV and what i found out so far:
In my case, the first row, here "Conflicts", was set to "Groupable=False", but the OLV itself was set to "ShowGroups=True".
FormatRow is fired in PostProcessOneRow, which is called according to source (Version: 2.9.1.0) in following logic:
protected virtual void PostProcessRows() {
// If this method is called during a BeginUpdate/EndUpdate pair, changes to the
// Items collection are cached. Getting the Count flushes that cache.
#pragma warning disable 168
// ReSharper disable once UnusedVariable
int count = this.Items.Count;
#pragma warning restore 168
int i = 0;
if (this.ShowGroups) {
foreach (ListViewGroup group in this.Groups) {
foreach (OLVListItem olvi in group.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
} else {
foreach (OLVListItem olvi in this.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
}
Since grouping failed, due to no groupable rows being present in OLV, the PostProcessOneRow in the if-body was not hit even once (foreach operated in "this.Groups" whichs count was 0).
Set "ShowGroups=False", works like a charm now.
I have a bunch of code that dynamicly creates some controls. It looks in a folder and lists the filenames in it. For each file in the folder it creates a checklistbox item, listbox item and two checkboxes. This is working great and as intended:
private void getAllFiles(string type)
{
try
{
string listPath = "not_defined";
if (type == "internal_mod")
{
int first_line = 76;
int next_line = 0;
int i = 0;
CheckBox[] chkMod = new CheckBox[100];
CheckBox[] chkTool = new CheckBox[100];
listPath = this.internalModsPath.Text;
string[] filesToList = System.IO.Directory.GetFiles(listPath);
foreach (string file in filesToList)
{
if (!internalModsChkList.Items.Contains(file))
{
internalModsChkList.Items.Add(file, false);
string fileName = Path.GetFileName(file);
internalModNameList.Items.Add(fileName);
//-----------------
// Draw Checkboxes
//-----------------
chkMod[i] = new CheckBox(); chkTool[i] = new CheckBox();
chkMod[i].Name = "modChk" + i.ToString(); chkTool[i].Name = "modChk" + i.ToString();
//chkMod[i].TabIndex = i; //chkTool[i].TabIndex = i;
chkMod[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top); chkTool[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top);
chkMod[i].Checked = true; chkTool[i].Checked = false;
chkMod[i].AutoCheck = true; chkTool[i].AutoCheck = true;
chkMod[i].Bounds = new Rectangle(549, first_line + next_line, 15, 15); chkTool[i].Bounds = new Rectangle(606, first_line + next_line, 15, 15);
groupBox7.Controls.Add(chkMod[i]); groupBox7.Controls.Add(chkTool[i]);
//-----------------
next_line += 15;
i++;
}
}
}
Now my problem is that I also want the user to be able to delete all these thing again based on the checklistbox' checked items.. I have no problems deleting the items in the checklistbox or the items in the listbox, but I want to remove the two checkboxes I create too ..
This is what I got to remove the items in the checklistbox, and the listbox
private void internalModListDel_btn_Click(object sender, EventArgs e)
{
int count = internalModsChkList.Items.Count;
for (int index = count; index > 0; index--)
{
if (internalModsChkList.CheckedItems.Contains(internalModsChkList.Items[index - 1]))
{
internalModsChkList.Items.RemoveAt(index - 1);
internalModNameList.Items.RemoveAt(index - 1);
groupBox7.Controls.Remove(modChk[index - 1]);
}
}
}
As you can see I have also tried to write something to remove the checkbox but it doesn't work and I have no idea how to make it work
Can you assist ?
Try using UserControls.
Use the ListBox controller to show those UserControls,
The user control can be built with those checkboxes, and the labels you want .
Another suggestion is to bind this list to an ObservableCollection which will contain the UserContorols you have created.
This way, it will be much more simlpe to add/remove/change the items inside.
I've created a number of buttons on a form based on database entries, and they work just fine. Here's the code for creating them. As you can see I've given them a tag:
for (int i = 0; i <= count && i < 3; i++)
{
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Tag = i;
this.Controls.Add(btnAdd);
}
I use these buttons for visualising a polling system. For example, I want the button to be green when everything is fine, and red when something is wrong.
So the problem I'm running into is referencing the buttons later so that I can change their properties. I've tried stuff like the following:
this.Invoke((MethodInvoker)delegate
{
// txtOutput1.Text = (result[4] == 0x00 ? "HIGH" : "LOW"); // runs on UI thread
Button foundButton = (Button)Controls.Find(buttonNumber.ToString(), true)[0];
if (result[4] == 0x00)
{
foundButton.BackColor = Color.Green;
}
else
{
foundButton.BackColor = Color.Red;
}
});
But to no avail... I've tried changing around the syntax of Controls.Find() but still have had no luck. Has anyone encountered this problem before or know what to do?
If you name your buttons when you create them then you can find them from the this.controls(...
like this
for (int i = 0; i <= count && i < 3; i++)
{
Button btnAdd = new Button();
btnAdd.Name="btn"+i;
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Tag = i;
this.Controls.Add(btnAdd);
}
then you can find it like this
this.Controls["btn1"].Text="New Text";
or
for (int i = 0; i <= count && i < 3; i++)
{
//**EDIT** I added some exception catching here
if (this.Controls.ContainsKey("btn"+buttonNumber))
MessageBox.Show("btn"+buttonNumber + " Does not exist");
else
this.Controls["btn"+i].Text="I am Button "+i;
}
Put these buttons in a collection and also set the name of the Control rather than using its tag.
var myButtons = new List<Button>();
var btnAdd = new Button();
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Name = i;
myButtons.Add(btnAdd);
To find the button use it.
Button foundButton = myButtons.Where(s => s.Name == buttonNumber.ToString());
Or Simply
Button foundButton = myButtons[buttonNumber];
In your case I would use a simple Dictionary to store and retrieve the buttons.
declaration:
IDictionary<int, Button> kpiButtons = new Dictionary<int, Button>();
usage:
Button btnFound = kpiButtons[i];
#Asif is right, but if you really want to utilize tag you can use next
var button = (from c in Controls.OfType<Button>()
where (c.Tag is int) && (int)c.Tag == buttonNumber
select c).FirstOrDefault();
I'd rather create small helper class with number, button reference and logic and keep collection of it on the form.
private void CreateNewControl()
{
List<Control> list = new List<Control>();
TableLayoutPanel layout = new TableLayoutPanel();
layout.Dock = DockStyle.Fill;
this.Controls.Add(layout);
layout.ColumnCount = 3;
layout.GrowStyle = TableLayoutPanelGrowStyle.AddRows;
for (int i = 0; i < 9; i++)
{
if (wantedType == DevExpress.XtraEditors.CheckEdit)
{
CheckBox chk = new CheckBox();
chk.Tag = i;
layout.Controls.Add(chk);
layout.AutoScroll = true;
}
if (wantedType == LabelControl)
{
Label chk = new Label();
chk.Tag = i;
layout.Controls.Add(chk);
layout.AutoScroll = true;
}
// I want to set the columnwidth of the layout so that when the labels are displayed they do not get clustered and look exactly like when displaying the checkboxes.How do I do it?
In general, what I do is:
Use the IDE in a 'prototype' project, to create a form with the controls in the positions that I want
Look at the source code created by the IDE (in the MyFormName.Designer.cs file) to see what source code is generated by the IDE to creat these controls
Create my own form in my real project, with hand-coded code that's based on what I learned from the prototype which I created using the IDE
// Loop through all the controls you want to add.
// Add a integer field that measures the highest width of each control like
int _iMaxWidth = 0;
for (int i=0; i < TotalControls.Count; ++i)
{
if ( control[i].Width > _iMaxWidth)
_iMaxWidth = control[i].Width
}
// Then you'll know what the width size of the column should be.
Col.Width = iMaxWidth + 2; // +2 to make things a little nicer.