How to add new item into listbox that using datasource? - c#

I create a winform application that contains 3 textbox (pcno, pcname and pcipadd), one listbox that is using a datasource and one button to add new item. I'm having a trouble to add an item to my listbox. I'm using this code on the add item button:
_pcno.Add(new PCNo() { PCNO = pcno.Text,
PCNAME = pcname.Text,
IPADDRESS = pcipadd.Text });
The code above adds the new item successfully, but the selected item in the listbox also been updated.
In details, I currently have a "PCN01" on my listbox. Then I go to my textbox (pcno.text) then write new value (example "PC02") and click the button to add item .What happens is the item is added but the "PC01" are also getting updated to "PC02". After reloading the form (re-open) all change back to normal, "PC01" with its value and "PC02" with its value. I just don't want the selected item on the listbox getting update while adding the new item. Any ideas?
Ok, to put this simplly, this is what I'm trying to do, you can try it, if you add new item the selected item also getting updated:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace PCListing
{
public partial class Form1 : Form
{
private BindingList<mylist> _pcno;
private ListBox listBox1;
private TextBox pcno;
private TextBox pcname;
private Button btnAdd;
public Form1()
{
InitializeComponent();
FlowLayoutPanel layout = new FlowLayoutPanel();
layout.Dock = DockStyle.Fill;
Controls.Add(layout);
listBox1 = new ListBox();
layout.Controls.Add(listBox1);
pcno = new TextBox();
layout.Controls.Add(pcno);
pcname = new TextBox();
layout.Controls.Add(pcname);
btnAdd = new Button();
btnAdd.Click += btnAdd_Click;
btnAdd.Text = "Add Item";
layout.Controls.Add(btnAdd);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
_pcno = new BindingList<mylist>();
_pcno.Add(new mylist() { pcno = "1", pcname = "PC01" });
_pcno.Add(new mylist() { pcno = "2", pcname = "PC02" });
listBox1.DisplayMember = "pcno";
listBox1.DataSource = _pcno;
pcno.DataBindings.Add("Text", _pcno, "pcno");
pcname.DataBindings.Add("Text", _pcno, "pcname");
}
private void btnAdd_Click(object sender, EventArgs e)
{
_pcno.Add(new mylist() { pcno =pcno.Text, pcname = pcname.Text });
}
public class mylist
{
public string pcname { get; set; }
public string pcno { get; set; }
}
}
}

The problem is caused by TextBox databindings.
pcno.DataBindings.Add("Text", _pcno, "pcno");
pcname.DataBindings.Add("Text", _pcno, "pcname");
In that form DataSource is updated when you edit values in text boxes.
You might consider changing those lines to:
pcno.DataBindings.Add("Text", _pcno, "pcno", false, DataSourceUpdateMode.Never);
pcname.DataBindings.Add("Text", _pcno, "pcname", false, DataSourceUpdateMode.Never);

Related

How to disable the automatic selection of the first item in ComboBox?

I have a form with a ComboBox, which is populated with 3 items.
When I add the statements: comboBox1.Text = "A"; and comboBox1.DroppedDown = true;
the first item of the drop-down list is automatically selected: the comboBox1.Text shows "Abc" in stead of "A".
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testComboBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
comboBox1.Text = "A";
comboBox1.DroppedDown = true;
}
ComboBox comboBox1;
private void PopulateComboBox()
{
comboBox1.Items.Add("Abc");
comboBox1.Items.Add("Abcd");
comboBox1.Items.Add("Abcde");
}
private void button_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
How can I disable the automatic selection of the first item in the Items collection of the ComboBox, so that the comboBox1.Text will show "A" and not "Abc"?
I am not looking for a one-time work-around. I need a GENERAL SOLUTION.
set this code comboBox1.SelectedText = null;
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
comboBox1.SelectedText = "A";
comboBox1.DroppedDown = true;
comboBox1.SelectedText = null;
}
With the help of the thread that Loathing pointed to, I copied the extension Class ComboBoxAutoSelectExtension and in the form I just added the line of code: ComboBoxAutoSelectExtension.AutoSelectOff(comboBox1);
If you copy the ComboBoxAutoSelectEx from the link in the comment, then the only thing you should have to do in your own Form1 code is:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
String text = "A";
comboBox1.Text = text;
comboBox1.Select(text.Length,1); // put cursor at the end of text
ComboBoxAutoSelectEx.AutoSelectOff(comboBox1); // Added
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
}
protected override void OnLoad(EventArgs e) { // Added
base.OnLoad(e);
comboBox1.DroppedDown = true;
}
ComboBox comboBox1;
private void PopulateComboBox()
{
comboBox1.Items.Add("Abc");
comboBox1.Items.Add("Abcd");
comboBox1.Items.Add("Abcde");
}
private void button_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
I see no way to disable auto selection of an item. I can only replace the wrong selection with the input text that was previously known. This bug occurs on both opening or closing the dropdown. Here is an example code when opening the dropdown.
// record
box_txt = comboBox1.Text;
box_pos = comboBox1.SelectionStart;
// drop down
comboBox1.DroppedDown = true;
// replace
comboBox1.Text = box_txt;
comboBox1.SelectionStart = box_pos;

Change visible state of DataGridView only given its name

I have a form application where multiple DataGridView objects are to be displayed (but not at once). They should be created on top of each other and it should then be possible to toggle the displayed DataGridView using a ComboBox.
I have a function which should create new DataGridView every time its called and then adds the name to the ComboBox:
private void readCSV(string DBname)
{
DataGridView tagDBname = new DataGridView();
tagDBname.Location = new System.Drawing.Point(24, 260);
tagDBname.Name = DBname;
tagDBname.Size = new System.Drawing.Size(551, 217);
tagDBname.TabIndex = 6;
tagDBname.Columns.Add("Column1", "Col1");
tagDBname.Columns.Add("Column2", "Col2");
tagDBname.Visible = false;
comboBoxTag.Items.Add(DBname);
}
Then I would like to change the visibility state of a DataGridView given the selected name from the ComboBox. This should be done in the function called when the index changes:
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
DataGridView tagDatabase = ? // Here the DataGridView should be selected given the name "selectedTagDB"
tagDatabase.Visible = true;
}
In the above, I do not know how to assign the DataGridView only given its name. Any help would be appreciated - even if it means that the selected approach is inappropriate of what I am trying to achieve. If the question is answered elsewhere, feel free to guide me in the right direction :)
I would store the gridviews in a dictionary by using the DB name as key;
private readonly Dictionary<string, DataGridView> _tagDBs =
new Dictionary<string, DataGridView>();
private void readCSV(string DBname)
{
DataGridView tagDBname = new DataGridView();
// Add the gridview to the dictionary.
_tagDBs.Add(DBname, tagDBname);
tagDBname.Name = DBname;
tagDBname.Location = new System.Drawing.Point(24, 260);
tagDBname.Size = new System.Drawing.Size(551, 217);
tagDBname.TabIndex = 6;
tagDBname.Columns.Add("Column1", "Col1");
tagDBname.Columns.Add("Column2", "Col2");
tagDBname.Visible = false;
this.Controls.Add(tagDBname); // Add the gridview to the form ot to a control.
comboBoxTag.Items.Add(DBname);
}
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
foreach (DataGridView dgv in _tagDBs.Values) {
dgv.Visible = dgv.Name == selectedTagDB; // Hide all gridviews except the selected one.
}
}
If you need to do something with the selected gridview, you can get it with:
if (_tagDBs.TryGetValue(selectedTagDB, out DataGridView tagDatabase)) {
// do something with tagDatabase.
}
Note: you must add the gridview to the form or to a container control on the form. E.g.
this.Controls.Add(tagDBname);
You can loop through all DataGridViews of the form to display the expected one using its name, while hidding the others ones.
This solution isn't pretty but works
private void ShowOneDataGridViewAndHideOthers(string name)
{
foreach (var DGV in this.Controls.OfType<DataGridView>())
{
DGV.Visible = DGV.Name == name;
}
}
And call it this way :
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
ShowOneDataGridViewAndHideOthers(selectedTagDB);
}
The method can be made a bit more generic this way :
private void ShowOneControlAndHideOthers<T>(string name, Control controls) where T : Control
{
foreach (var control in controls.Controls.OfType<T>())
{
control.Visible = control.Name == name;
}
}
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
ShowOneControlAndHideOthers<DataGridView>(selectedTagDB, this);
}

Retrieving value from combo box selected item

I am using Windows Application.I Put some data as direct values in combo box.I defined var type to combo box.I put these combo box on form load.Now I want to retrieve the value of selected item on my button2_click event and I tried below code to retrieve it,but it giving me error of The name comboBox does not exist in current context.Can any one suggest me how to fix it.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
// Initialize combo box
var comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
//Add file in ListBox.
listBox1.Items.Add(file);
}
}
else
{
// listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
}
}
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}
comboBox was local variable in Form1 .ctor. You can't access it from another method
options:
1) access to the control by name
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
...
}
2) make it a private member of the form as controls normally are, if they are created in designer
ComboBox comboBox;
public Form1()
{
InitializeComponent();
// Initialize combo box
comboBox = new ComboBox() {...};
...
}
Currently the Combobox appears to be a local variable. Try to make it a global field variable and you should be able to access it.

How to pass data between forms?

I am developing a desktop application in which I want to get information from user. If user selects particular radio button then I am opening a new form in popup in which I have placed checked list box. After selecting values from check box I want to access selected value in the previous form. Below are images that can clear idea.
When user click on radio button in "Enable conent type" (as highlighted in the screen) a new form in popup is open to select values from checked list box. After selecting desired value , press "Select" button from Select Content Type form.
Now the form will be hidden but I want to get the selected values in the form "Create Lists".
My code for Radio Button event is:
private void rdbEnableCtypeYes_CheckedChanged(object sender, EventArgs e)
{
if (rdbEnableCtypeYes.Checked)
{
lblSelectContentType.Visible = true;
frmSelectContentType selectContentType = new frmSelectContentType();
selectContentType.rootWebUrl = rootWebUrl;
selectContentType.MdiParent = this.MdiParent;
selectContentType.StartPosition = FormStartPosition.CenterScreen;
selectContentType.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
selectContentType.Show();
}
else
{
lblSelectContentType.Visible = false;
cmbContentType.Visible = false;
}
}
My code for form of Select content type is:
public string rootWebUrl = string.Empty;
XDocument contentTypeFile = XDocument.Load(FilePaths.ContentTypesFilePath);
private void frmSelectContentType_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(rootWebUrl))
{
if (contentTypeFile != null)
{
XElement xSiteCollection = contentTypeFile.Descendants(XmlElements.SiteCollection).Where(x => x.Attribute(XmlAttributes.Url).Value.Equals(rootWebUrl)).FirstOrDefault();
if (xSiteCollection != null)
{
IEnumerable<XElement> xContentTypes = xSiteCollection.Descendants(XmlElements.ContentType);
if (xContentTypes.OfType<XElement>().Count() > 0)
{
foreach (XElement xContentType in xContentTypes)
{
ComboboxItem item = new ComboboxItem();
item.Text = xContentType.Attribute(XmlAttributes.Name).Value;
item.Value = xContentType.Attribute(XmlAttributes.Id).Value;
lstContenType.Items.Add(item);
}
}
}
}
}
}
What should I do?
Try This.
Select Content Type Form
private List<string> _selectedItems = new List<String>();
public List<string> SelectedItem
{
get {return _selectedItems;}
}
private void btnSelect_Click(object sender, EventArgs e)
{
for(int i=0; i<lst.Items.Count;i++)
{
if (lstContenType.GetItemCheckState(i) == CheckState.Checked)
_selectedItems.Add(lst.Items[i].ToString());
}
this.Close();
}
Create List Form
private void rdoEnableCntType_Checked(object sender, EventArgs e)
{
if (rdoEnableCntType.Checked = true)
{
FrmConentType frm = new FrmConentType();
frm.ShowDialog();
List<string> list = frm.SelectedItems;
//Place your code to use selected items
}
}
You can pass data in the Constructor of FormB. For example:
//Default Constructor
public FormB()
{
InitializeComponent();
}
// Overloaded Constructor
public FormB(string parameter1, string parameter2, string parameter3)
{
InitializeComponent();
}
For example:
public FormB(bool RbuttonChecked)
{
InitializeComponent();
if(RbuttonChecked)
{
//Code
}
}
Invoke FormB from FormA like:
FormB obj=new FormB(Rbtn.checked); //Invoking the overloaded constructor
obj.Show();
You can defined a list in the main form to store items user selected in "Select Content Type" windows. When user have finished the window "Select Content Type", you add selected items to the variable.
In Form "Create List" class:
public List<ContentType> selectedContentTypes = new List<ContentType>();
When user press "Select" button in form "Select Content Type", add items to the variable:
// For each selected items in the listbxo {
frmCreateList.selectedContentTypes.Items.Add(itemId);
// }
If you can post your source code, it would be easier to help.

Why am I getting Stale Data in my databound ComboBox?

I have a form with 2 databound listboxes and two databound comboboxes. I'm using typed datasets. The controls are bound to a pair of tables with the following schema and data from this schema. One listbox and one comboBox are bound to the bar table; the other listbox and comboBox are bound to the foo table.
When the SelectedIndexChanged Event fires for the foo listBox I get the current value for the Selected Text in the Bar listBox and comboBox.
However, when I use the foo comboBox and try to access the barComboBox.SelectedText inside the FooComboBox_SelectedIndexChanged event I get the previously selected value from SelectedText instead of the new value. The BarListBox.Selected gives me the current value.
Note that I use the FooListBox to do the selection, both event handlers function as expected.
Can anyone explain what's going on here and how to work around this?
Form Screenshot w/sample data:
The dataset designer:
The form1.cs code:
//Standard using statements and namespace info
public partial class Form1 : Form
{
//Loading DataSets and initializing here
private void FooListBox_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("The value in the bar ListBox is {0}", barListBox.Text);
}
private void FooComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("The value in the bar comboBox is {0}", barComboBox.Text);
}
}
I didn't find any behaviour as you Explained.
pleas check this code , Please do correct me reproduced code is wrong.
I have used Combo Box items and ListBox items are added in FormLoad as DataSource from Some webServiceMethod
in Form1.Designer.cs
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(32, 55);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(188, 21);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(261, 55);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(255, 95);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
*in Form1.cs*
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("The value in the bar comboBox is "+ comboBox1.Text);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("The value in the bar comboBox is "+ listBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
WebServiceRef.CM_ServiceSoapClient soapClient = new WebServiceRef.CM_ServiceSoapClient();
comboBox1.DataSource = soapClient.GetAllCategories();
listBox1.DataSource = soapClient.GetAllCategories();
}
I have changed the Data According to DataSource form WebService Method, Still I didn't find any issues as you exaplined your beahaviour.

Categories