What am I doing wrong here? be gentle.
For CheckedListBox, I can update the items simply by using:
private void button3_Click(object sender, EventArgs e)
{
checkedListBox4.Items.Add("whatever"); //or use an object
}
works great, but what I want to do is send the CheckedListItem a set of items from method within another class
So, I set up another class something:form1 that has a delegate that points to a method that I call\invoke
The delegate calls\invokes this way:
public delegate void m_del(List<DirectoryInfo> ww, string rr);
somewhere else in the code:
m_del methtouse = new m_del(listme)
public void listme(List<DirectoryInfo> fi, string mypath)
{
foreach (DirectoryInfo j in fi)
{
mypath = null; //mypath used by another method
try
{
NewCheckboxListItem cb1 = new NewCheckboxListItem();
cb1.Tag = j.Name;
cb1.Text = j.Name;
checkedListBox4.Items.Add(cb1);
}
catch (Exception w)
{
MessageBox.Show(w.Message);
}
}
}
public class NewCheckboxListItem
{
// define a text and
// a tag value
public string Text;
public string Tag;
// override ToString(); this
// is what the checkbox control
// displays as text
public override string ToString()
{
return this.Text;
}
}
methtouse( a List<DirectoryInfo> ww, a string rr)
{}
What happens is the Item collection in the checkedListBox4 is updated and has as many value as i send it, but it will not draw the item\show the item
I have tried calling a checkedListBox4_datavaluememberchanged method and a few other checkedListBox4_changed events but once again the items in the collection are updated but they do not appear in the CheckedListBox
I think its something to do with it not having eventargs
Is there an easy way to do a side by side comparison of ALL the attributes, events, properties of a successful CheckedListBox with that of an unsuccessful CheckedListBox (programmatically)
Note: The class inherits from form1 where the CheckedListBox is located, and the methods access is set to public.
What you are missing is to tell the checkedListBox what the value is supposed to be for that object.
checkedListBox4.ValueMember = "Text";
That tells the CheckedListBox to use the member matching that exact string as the display value.
https://stackoverflow.com/a/2023338/455536
http://msdn.microsoft.com/en-us/library/3yx132k0(v=vs.110).aspx
A string that specifies the property of the data source from which to draw the value.
Related
I have a subclassed Button with a couple of properties
public class ZButton : Button
{
private string UIB = "I";
public int _id_ { get; set; }
public int rowIndex { get; set; }
protected override void OnClick(EventArgs e)
{
Form frmNew = new Form(UIB);
frmNew.ShowDialog();
base.OnClick(e);
}
}
I placed that button on the form and here is the code for that button in the form.
private void zButton1_Click(object sender, EventArgs e)
{
rowIndex = dataGridView1.CurrentRow.Index;
_id_ = Convert.ToInt16( dataGridView1["id_city", rowIndex].Value.ToString());
}
I cant access those properties (rowIndex) and (id) and compiler gives errors
The name 'rowIndex' does not exist in the current context
I am rather new to C# so I must be missing something obviuos.
rowIndex and _id_ are properties of your zButton, they are not accesible directly in your form. So if you need to access them in the click event, you have to cast the sender to a zButton and access the properties of that instance.Something like this:
private void zButton1_Click(object sender, EventArgs e)
{
zButton but=(zButton)sender;
but.rowIndex = dataGridView1.CurrentRow.Index;
but._id_ = Convert.ToInt16(dataGridView1["id_city",but.rowIndex].Value.ToString());
}
If method zButton1_Click is a member of your form class, then it can directly access properties of the same class or its ancestor classes, not properties of aggregated objects like your button.
In order to access your button's properties, you should explicitly specify which object's properties you are trying to access. This means that if you want to access a property of an aggregated button zButton1, you should replace
dataGridView1["id_city", rowIndex]
with
dataGridView1["id_city", zButton1.rowIndex]
cast your sender to button.
var button = sender as zButton;
if (button != null)
{
button.rowIndex ...
...
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What I want is to type in a textbox before I start my packet sniffer to only show me results that I want. This is what I have but it isn't working. I want this listview to just show port 3074 using a textbox does anyone know how to do this? This is a packet sniffer
(source: gyazo.com)
Anyone know how I can do that?
This is what I am using
namespace Network.Packet.Analyzer.App.Forms.Main
{
public partial class FrmAnalyzer : Form, IAnalyzer
{
public FormaAnalyzerPresenter _presenter;
public FrmAnalyzer()
{
InitializeComponent();
_presenter = new FormaAnalyzerPresenter(this);
}
//callled when ListView control selection being made
private void lstReceivedPackets_SelectedIndexChanged(object sender, EventArgs e)
{
_presenter.CreateDetailedTree();
}
//start button click event method
private void toolStripButton1_Click(object sender, EventArgs e)
{
_presenter.StartClicked();
}
//stop button click event method
private void tbtnStop_Click(object sender, EventArgs e)
{
_presenter.StopClicked();
}
private void Form1_Load(object sender, EventArgs e)
{
_presenter.ApplicationStarted();
}
// clear all button click event method
// clearing buffer,listvie control,and treeview
private void tbtnClearAll_Click(object sender, EventArgs e)
{
_presenter.ClearAllClicked();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
ApplicationClose();
}
private void menuAlwaysOnTop_Click(object sender, EventArgs e)
{
_presenter.TopMostClicked();
}
#region IAnalyzer Members
public ListView ListReceivedPackets
{
get { return lstReceivedPackets; }
}
public ListView ListOpenPorts
{
get
{
return lstOpenPorts;
}
}
public ProgressBar ProgressBufferusage
{
get { return progressBufferUsage; }
}
public TreeView TreePackedDetails
{
get { return treePacketDetails; }
}
public void SetTotalPacketReceivedText(string strNumber)
{
if (strNumber != null)
lblTotalPkgsReceived.Text = strNumber;
}
public void SetBufferUsage(string strNumber)
{
if (strNumber != null)
lblBufferUsage.Text = strNumber;
}
public void SetReadyText(string text)
{
if (text != null)
lblStripReady.Text = text;
}
public bool ButtonStartEnabled
{
get { return tbtnStar.Enabled; }
set { tbtnStar.Enabled = value; }
}
public bool ButtonStopEnabled
{
get { return tbtnStop.Enabled; }
set { tbtnStop.Enabled = value; }
}
public bool TopMostChecked
{
get
{
return topMostMenuItem.Checked;
}
set
{
topMostMenuItem.Checked = value;
}
}
public bool FormShowAsTopMost
{
get
{
return this.TopMost;
}
set
{
this.TopMost = value;
}
}
public void ApplicationClose()
{
this.Close();
}
public StartupInfo StartupInformation
{
get
{
return _presenter.StartupInformation;
}
set
{
_presenter.StartupInformation = value;
}
}
public void ShowErrorMessage(string message)
{
MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowWarningMessage(string message)
{
MessageBox.Show(message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
public void ShowDefaultErrorMessage()
{
MessageBox.Show("Unexpected error has acquired", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowDefaultErrorMessage(Exception ex)
{
MessageBox.Show(String.Format("Unexpected error has acquired. Error message: {0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void ShowErrorMessage(string message, Exception ex)
{
MessageBox.Show(String.Format("{0}. Error message: {1}", message, ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void Invoke(Action act)
{
this.Invoke(new MethodInvoker(delegate { act(); }));
}
private void button1_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
#endregion
This is the other part: pastebin.com/rPWMJHCe
Okay, seeing your code from pastebin, i will keep my answer rather simple. My answer is most certainly not the best and not the most elegant, and you will certainly still hit a wall here and there, but making it better and easier to work with would most likely require abandoning ListView in favor of a more capable control (such as DataGridView, for example). Anyway...
For the example given below, i'll pick the ListView ListOpenPorts. But of course you can adapt this approach to other ListViews as well, just pay attention to keep track of where which data is stored inside the ListViewItems.
The basic idea of a filtered content display is something ListView doesn't really like. It is not so much the filtering itself, but the fact that all items must be somewhere when we change or switch off filtering. What makes ListView suck so much in this regard is that it insists to maintain the list of items internally instead of giving us the opportunity to control and swap that list easily (hence me pointing towards DataGridView earlier).
The approach involves maintaining another private list _listOpenPortItems in the class FrmAnalyzer which will keep all 'open port' ListViewItems. This is necessary so our code can access them and feed them back into the lstOpenPorts ListView whenever the filtering is switched off or changed.
private readonly List<ListViewItem> _listOpenPortItems = new List<ListViewItem>();
To always have the correct items in the _listOpenPortItems list requires to not access ListOpenPorts.Items directly. Instead, methods will be implemented in the class FrmAnalyzer which will realize equivalent functions for any function used on ListOpenPorts.Items before. Those methods manipulate the private list _listOpenPortItems and also add/remove items to/from the actual ListView control depending on the filter settings.
Also note the two properties IsPortFilterEnabled and PortToFilter, which control filtering and which i will explain a bit later.
public void AddOpenPortItem(ListViewItem openPortItem)
{
_listOpenPortItems.Add(openPortItem);
if (!IsPortFilterEnabled || PortToFilter == openPortItem.SubItems[3])
lstOpenPorts.Items.Add(openPortItem);
}
public void RemoveOpenPortItem(ListViewItem openPortItem)
{
_listOpenPortItems.Remove(openPortItem);
if (!IsPortFilterEnabled || PortToFilter == openPortItem.SubItems[3])
lstOpenPorts.Items.Remove(openPortItem);
}
//...Also implement here methods for all other functions of
//...ListOpenPorts.Items you used before (such as RemoveByKey, ContainsKey, etc...)
//...which will have to realize the equivalent function on _listOpenPortItems.
//...Any method which can potentially alter _listOpenPortItems will have to have a
//...code snippet like:
// if (!IsPortFilterEnabled || PortToFilter == openPortItem.SubItems[3])
// lstOpenPorts.Items.XXXXXX(openPortItem);
//
//...(where XXXXXX is the appropriate method of lstOpenPorts.Items)
(Note that i here assume the port number being the subitem with index 3.)
With those methods implemented, just replace all direct accesses of ListOpenPorts.Items with the respective method calls. For example:
_view.Invoke(() => _view.ListOpenPorts.Items.Remove(item));
would be replaced with:
_view.Invoke(() => _view.RemoveOpenPortItem(item));
This code change sound like difficult work, but it is actually not that hard and just a question of finding all usages of "ListOpenPorts"/"ListOpenPorts.Items" - a simple text search through your whole source code is the bigger part of the job.
To control the filter we will use the two properties i already mentioned: PortToFilter, a String property which will hold the port number to filter for; and IsPortFilterEnabled, a bool property denoting whether the filter is enabled or not.
Both properties are, like the methods above, implemented in the class FrmAnalyzer.
public bool IsPortFilterEnabled
{
get { return _isPortFilterEnabled; }
set
{
if (_isPortFilterEnabled != value)
{
_isPortFilterEnabled = value;
RefreshOpenPortListView();
}
}
}
private bool _isPortFilterEnabled = false;
public string PortToFilter
{
get { return _portToFilter ; }
set
{
//
// Note that setting PortToFilter will turn on the filter
//
if(!_isPortFilterEnabled || _portToFilter != value)
{
_portToFilter = value;
RefreshOpenPortListView();
}
}
}
private string _portToFilter = "0";
Remark: It would be better to handle port numbers as what they are - int numbers, not strings. But since you already use strings for port numbers, i chose the string data type here, too.
You might notice the calls of method RefreshOpenPortListView. This is a method which updates lstOpenPorts.Items according to the filter settings.
private void RefreshOpenPortListView()
{
//
// Note that this method does not preserve the current selection in the List View.
// If you need to preserve it, save the current selection here and restore it
// at the end of this method again.
//
IEnumerable<ListViewItem> itemsForListView =
(_isPortFilterEnabled) ?
_listOpenPortItems.Where(item => PortToFilter == item.SubItems[3])
: _listOpenPortItems;
lstOpenPorts.BeginUpdate();
_lstOpenPorts.Itmes.Clear();
foreach(ListViewItem item in _itemsForListView)
_lstOpenPorts.Add(openPortItem);
_lstOpenPorts.EndUpdate();
}
(Note that i here assume the port number being the subitem with index 3.)
Finally, how do you set IsPortFilterEnabled and PortToFilter? Here one idea briefly outlined, but there a numerous different ways of how to do that:
Let a checkbox toggle the value of IsPortFilterEnabled. This checkbox basically enables/disables the filtered view.
Let a (numerical) textbox dump its content into PortToFilter. This textbox contains the port number to filter for. Note that (according to my suggested implementation) whenever the textbox transfers its content to PortToFilter, the filtered view is enabled and updated.
You want to sort or filter?, your title says sort, but your description says "to just show those results"
If your Listview is bound to a DataTable, then you can filter or sort using the DefaultView property.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
dtItems.DefaultView.Sort = "ID";
else
dtItems.DefaultView.Sort = "Name";
MyBindMethod(dtItems);
}
Or if you want to filter by ID
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dtItems.DefaultView.RowFilter = "ID = '" + comboBox1.SelectedValue + "'";
MyBindMethod(dtItems);
}
I am working with lists. I am now experimenting with determining the positions of items inside list: first, next and last. I have been able to determine the first and last position of items in my list through function getPostion and displaying the item name through a Label. Three buttons in my form: ShowFirstItem ShowNextItem and ShowLastItem show the corresponding item in a label. I am having problems for displaying the next item. I have special method for next called GetNextTree. When I am calling this method from inside ShowNextItem click I get this error: Cannot implicitly convert type 'TreeFarm.Form1.fruit_trees' to 'string'. How can avoid this error and display the item currently pointed to?
namespace TreeFarm {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
public class ListForTrees {
public fruit_trees GetNextTree() {
//save currently pointed tree
fruit_trees tree = this.current_tree;
if (tree != null) {
//move current_tree to the next tree, to be returned next time
current_tree = current_tree.next_tree;
//return saved tree object
}
return tree;
}
}
private void ShowNextItem_Click(object sender, EventArgs e) {
//Show Next Item
labelSpecificTree.Text = mainlist.GetNextTree();
}
}
It's because your GetNextTree() method returns a fruit_trees object, but you're trying to set that return value to a String (the Text property of labelSpecificTree) inside of ShowNextItem. You'll need to do something like this instead:
private void ShowNextItem_Click(object sender, EventArgs e)
{
//Show Next Item
labelSpecificTree.Text = mainlist.GetNextTree().ToString();
}
You need to convert your fruit_tree to a string, and you may also want to consider the null case:
private void ShowNextItem_Click(object sender, EventArgs e)
{
//Show Next Item
fruit_trees nextTree = mainlist.GetNextTree();
if (nextTree == null)
{
labelSpecificTree.Text = "No more trees!";
}
else
{
labelSpecificTree.Text = nextTree.ToString();
}
}
EDIT: As MattSmith pointed out, perhaps you'd prefer to use nextTree.GetTreeType instead to match your other methods. It's up to you.
I have a second window which opens when a certain staffname is searched for, this window prompts you to choose between the 2 staff members with the same name. The window then needs to return a value to the parent window to populate a datatemplate with relating data from the xml file.
I've tried to create a string which will be updated with a value depending on which button is clicked, this string can then be returned to the calling method on the first window and populate binding data in the Linq to Xml query.
But when it runs it causes a stackoverflow exception and that it could be an infinite loop. I'm not sure enough about c# to know what to change.
public partial class Choice : Window
{
private string StaffChoice;
public Choice()
{
InitializeComponent();
}
public string staffChoice
{
get { return this.StaffChoice; }
set { staffChoice = StaffChoice; }
}
private void btnMRG_Click(object sender, RoutedEventArgs e)
{
StaffChoice = "MRG";
this.Close();
}
private void btnRPG_Click(object sender, RoutedEventArgs e)
{
StaffChoice = "RPG";
this.Close();
}
}
Any help or suggestions would be great!
Thanks in advance!
Firstly, your naming conventions are wrong - the field should be called staffChoice and the property should be called StaffChoice. Please read the .NET naming conventions for more information. However, now look at your property closely:
public string staffChoice
{
get { return this.StaffChoice; }
set { staffChoice = StaffChoice; }
}
What do you think the setter does? There are two problems with it:
It ignores the value that you're trying to set it to.
It calls itself recursively.
You could fix this by keeping the manually-declared field, fixing the naming conventions, and changing the property to set the variable to value like this:
private string staffChoice;
public string StaffChoice
{
get { return staffChoice; }
set { staffChoice = value; }
}
However, it would be simpler to use an automatically implemented property:
public string StaffChoice { get; set; }
This will create the backing field and the getter/setter for you automatically.
The simplest way is to declare a property like this...
public string StaffChoice { get; set; }
your problem is you are basically calling the property setter from within the same setter - thus you have a recursive loop. You could change your code like this to make it work...
private string StaffChoice;
public string staffChoice
{
get { return this.StaffChoice; }
set { StaffChoice = value; }
}
Your setter isn't right, you are assigning a value to itself (causing the infinite loop) and not using value.
You should change your code to this, your naming convention looked backwards so I corrected it, hope you don't mind:
private string staffChoice;
public Choice()
{
InitializeComponent();
}
public string StaffChoice
{
get { return staffChoice; }
set { staffChoice = value; }
}
private void btnMRG_Click(object sender, RoutedEventArgs e)
{
staffChoice = "MRG";
this.Close();
}
private void btnRPG_Click(object sender, RoutedEventArgs e)
{
staffChoice = "RPG";
this.Close();
}
Your property should be:
public string staffChoice
{
get { return this.StaffChoice; }
set { this.StaffChoice = value; }
}
In your code you are calling the setter again in the setter - hence the infinite recursion.
However, as you are not doing anything special in the setter (like notifying the UI that the property has changed you could simply have:
public string staffChoice { get; set; }
This "auto property" is a little cleaner.
(BTW: the normal practice is to have the back variable starting with a lower case letter and the public property starting with an upper case one. However, if you are consistent in your application it doesn't really matter.)
I have a CustomTextBox which inherits from TextBox and overwrites the OnValidating method to allow empty strings. CustomTextBox is bound to Property Price in Domain.
public class CustomTextBox
{
protected override void OnValidating(...)
{
if(Text=="")
{
Text = null;
return;
}
base.OnValidating(e);
}
}
public class Domain
{
public System.Nullable<decimale> Price
{ ... }
}
All works well except that this prevents users froming setting Price to null. Text=null; did not propogate to the domain object. Is there a way to reset Price back to null when user clears out the TextBox?
If you are using Binding to propagate values to the domain object, then you should put this logic in the Parse event instead.
// Add binding
var b = new Binding("Text", myDataSource, "BoundProperty");
b.Parse += OnNullableTextBindingParsed;
myTextBox.DataBindings.Add(b);
// Sample parse handler
private void OnNullableTextBindingParsed(object sender, ConverterEventArgs e)
{
if (e.Value == String.Empty) e.Value = null;
}