CheckListBox for each - c#

I'm losing my mind with CheckListBox, I tried to get all of my checked items in my list. Here the code I use, with the button which are on my User interface:
public partial class formPCRBaseline : Form
{
public formPCRBaseline(List<GetBaselineSectionTasks> m_objPCRCheck)
{
InitializeComponent();
setDefaults(m_objPCRCheck);
}
private void setDefaults(List<GetBaselineSectionTasks> m_objPCRCheck)
{
checkedListBox.BackColor = Color.White;
List<GetBaselineSectionTasks> m_objCheckeditem = new List<GetBaselineSectionTasks>();
int i= 0;
foreach (GetBaselineSectionTasks i_objPCRCheck in m_objPCRCheck)
{
checkedListBox.Items.Add(i_objPCRCheck.taskname);
}
}
private void buttonConfirm_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void buttonClose_Click_1(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
public List<GetBaselineSectionTasks> GetCheckedItems()
{
List<GetBaselineSectionTasks> m_objCheckeditem = new List<GetBaselineSectionTasks>();
m_objCheckeditem.AddRange(checkedListBox.CheckedItems.OfType<GetBaselineSectionTasks>());
return m_objCheckeditem;
}
}
}
And here the class I use to Initialize my component:
private void InitializeComponent()
{
this.buttonClose = new System.Windows.Forms.Button();
this.buttonConfirm = new System.Windows.Forms.Button();
this.checkedListBox = new System.Windows.Forms.CheckedListBox();
this.SuspendLayout();
//
// buttonClose
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.buttonClose.Location = new System.Drawing.Point(306, 299);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(100, 30);
this.buttonClose.TabIndex = 0;
this.buttonClose.Text = "Cancel";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click_1);
//
// buttonConfirm
//
this.buttonConfirm.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonConfirm.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.buttonConfirm.Location = new System.Drawing.Point(192, 299);
this.buttonConfirm.Name = "buttonConfirm";
this.buttonConfirm.Size = new System.Drawing.Size(100, 30);
this.buttonConfirm.TabIndex = 4;
this.buttonConfirm.Text = "OK";
this.buttonConfirm.UseVisualStyleBackColor = true;
this.buttonConfirm.Click += new System.EventHandler(this.buttonConfirm_Click);
//
// checkedListBox
//
this.checkedListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkedListBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 5.5F);
this.checkedListBox.FormattingEnabled = true;
this.checkedListBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.checkedListBox.Location = new System.Drawing.Point(16, 41);
this.checkedListBox.Name = "checkedListBox";
this.checkedListBox.Size = new System.Drawing.Size(394, 244);
this.checkedListBox.TabIndex = 5;
//
// formPCRBaseline
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(418, 334);
this.Controls.Add(this.checkedListBox);
this.Controls.Add(this.buttonConfirm);
this.Controls.Add(this.buttonClose);
this.Name = "formPCRBaseline";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "PMIS – Project Planning";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.Button buttonConfirm;
private System.Windows.Forms.CheckedListBox checkedListBox;
But it doesn't work, when I use my breakpoint, it reached the foreach, I have two selected items but it doesn't get in
Any idea of what I could do?

Are you looking for CheckedItems / CheckedIndices property? Providing that CheckListBox - checkedListBox contains GetBaselineSectionTasks items, i.e. you fill it like this:
checkedListBox.Items.Add(new GetBaselineSectionTasks(...));
...
checkedListBox.Items.Add(new GetBaselineSectionTasks(...));
You can put
List<GetBaselineSectionTasks> m_objCheckeditem = new List<GetBaselineSectionTasks();
...
m_objCheckeditem.AddRange(checkedListBox.CheckedItems.OfType<GetBaselineSectionTasks>());
or if you want to create a list in one go:
List<GetBaselineSectionTasks> result = checkedListBox.CheckedItems
.OfType<GetBaselineSectionTasks>()
.ToList();
Edit: If are working with strings i.e. you fill checkedListBox like this:
checkedListBox.Items.Add("Some Value");
...
checkedListBox.Items.Add("Some other value");
you can loop over checked items and when trying to foind out the corresponding
foreach (int index in checkedListBox.CheckedIndices) {
string taskName = Convert.ToString(checkedListBox[index]);
// Now you have item index and item text (which is taskName). Let's try filling the list
// We can try finding the item by string
for (var item in m_objPCRCheck) {
if (item.taskname == taskName) {
m_objCheckeditem.Add(item);
break;
}
}
// Or (alternatively) you can trying to get index-th item:
// m_objCheckeditem.Add(m_objPCRCheck[index]);
}

Related

Having trouble displaying a list of transactions to a list box in VisualStudios2019 winforms C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 13 days ago.
Improve this question
I know I'm butchering the transaction class. I just have no idea what to do. Nothing gets displayed when I run the form and hit add new transaction. I appreciate any help here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccountBalance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnNewTran_Click(object sender, EventArgs e)
{
string strTransactionType = "";
if (rbDeposit.Checked)
{
strTransactionType = rbDeposit.Text;
}
else
{
strTransactionType = rbWithdrawal.Text;
}
Transaction newTransaction = new Transaction();
newTransaction.Amount = decimal.Parse(txtTAmount.Text);
newTransaction.Type = strTransactionType;
newTransaction.Date = txtTDate.Text;
lstTransactions.Items.Add(newTransaction);
decimal decBalance = decimal.Parse(lblCBalance.Text);
if (newTransaction.Type == "Deposit")
{
decBalance += newTransaction.Amount;
lblCBalance.Text = decBalance.ToString("c");
}
else
{
decBalance -= newTransaction.Amount;
lblCBalance.Text = decBalance.ToString("c");
}
if (decBalance < 0)
{
lblCBalance.ForeColor = Color.Red;
}
rbDeposit.Checked = false;
rbWithdrawal.Checked = false;
txtTAmount.Clear();
txtTDate.Clear();
txtTAmount.Focus();
}
private void btnRemTran_Click(object sender, EventArgs e)
{
int intSelectedIndex = lstTransactions.SelectedIndex;
Transaction selectedTransaction = (Transaction)lstTransactions.SelectedItem;
lstTransactions.Items.RemoveAt(intSelectedIndex);
decimal decBalance = decimal.Parse(lblCBalance.Text);
if (selectedTransaction.Type == "Deposit")
{
decBalance -= selectedTransaction.Amount;
lblCBalance.Text = decBalance.ToString("c");
}
else
{
decBalance += selectedTransaction.Amount;
lblCBalance.Text = decBalance.ToString("c");
}
if (decBalance >= 0)
{
lblCBalance.ForeColor = Color.Black;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
rbDeposit.Checked = false;
rbWithdrawal.Checked = false;
txtTAmount.Clear();
txtTDate.Clear();
txtTAmount.Focus();
}
private void lstTransactions_Click(object sender, EventArgs e)
{
Transaction selectedTransaction = (Transaction)lstTransactions.SelectedItem;
if (selectedTransaction.Type == "Deposit")
{
rbDeposit.Checked = true;
}
else
{
rbWithdrawal.Checked = true;
}
txtTAmount.Text = selectedTransaction.Amount.ToString("c");
txtTDate.Text = selectedTransaction.Date;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
public class Transaction
{
internal decimal Amount;
internal string Type;
internal string Date;
}
}
namespace AccountBalance
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblTDate = new System.Windows.Forms.Label();
this.txtTDate = new System.Windows.Forms.TextBox();
this.lblTAmount = new System.Windows.Forms.Label();
this.txtTAmount = new System.Windows.Forms.TextBox();
this.lblTType = new System.Windows.Forms.Label();
this.rbDeposit = new System.Windows.Forms.RadioButton();
this.rbWithdrawal = new System.Windows.Forms.RadioButton();
this.rbServFee = new System.Windows.Forms.RadioButton();
this.lblPayee = new System.Windows.Forms.Label();
this.txtPayee = new System.Windows.Forms.TextBox();
this.lblCheckNum = new System.Windows.Forms.Label();
this.txtCheckNum = new System.Windows.Forms.TextBox();
this.lblCBalance = new System.Windows.Forms.Label();
this.txtCBalance = new System.Windows.Forms.TextBox();
this.lstTransactions = new System.Windows.Forms.ListBox();
this.btnNewTran = new System.Windows.Forms.Button();
this.btnRemTran = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblTDate
//
this.lblTDate.AutoSize = true;
this.lblTDate.Location = new System.Drawing.Point(12, 9);
this.lblTDate.Name = "lblTDate";
this.lblTDate.Size = new System.Drawing.Size(104, 13);
this.lblTDate.TabIndex = 0;
this.lblTDate.Text = "Date of Transaction:";
//
// txtTDate
//
this.txtTDate.Location = new System.Drawing.Point(15, 25);
this.txtTDate.Name = "txtTDate";
this.txtTDate.Size = new System.Drawing.Size(100, 20);
this.txtTDate.TabIndex = 1;
//
// lblTAmount
//
this.lblTAmount.AutoSize = true;
this.lblTAmount.Location = new System.Drawing.Point(263, 9);
this.lblTAmount.Name = "lblTAmount";
this.lblTAmount.Size = new System.Drawing.Size(105, 13);
this.lblTAmount.TabIndex = 0;
this.lblTAmount.Text = "Transaction Amount:";
//
// txtTAmount
//
this.txtTAmount.Location = new System.Drawing.Point(266, 25);
this.txtTAmount.Name = "txtTAmount";
this.txtTAmount.Size = new System.Drawing.Size(100, 20);
this.txtTAmount.TabIndex = 2;
//
// lblTType
//
this.lblTType.AutoSize = true;
this.lblTType.Location = new System.Drawing.Point(473, 9);
this.lblTType.Name = "lblTType";
this.lblTType.Size = new System.Drawing.Size(93, 13);
this.lblTType.TabIndex = 0;
this.lblTType.Text = "Transaction Type:";
//
// rbDeposit
//
this.rbDeposit.AutoSize = true;
this.rbDeposit.Location = new System.Drawing.Point(481, 28);
this.rbDeposit.Name = "rbDeposit";
this.rbDeposit.Size = new System.Drawing.Size(61, 17);
this.rbDeposit.TabIndex = 3;
this.rbDeposit.TabStop = true;
this.rbDeposit.Text = "Deposit";
this.rbDeposit.UseVisualStyleBackColor = true;
//
// rbWithdrawal
//
this.rbWithdrawal.AutoSize = true;
this.rbWithdrawal.Location = new System.Drawing.Point(481, 51);
this.rbWithdrawal.Name = "rbWithdrawal";
this.rbWithdrawal.Size = new System.Drawing.Size(78, 17);
this.rbWithdrawal.TabIndex = 4;
this.rbWithdrawal.TabStop = true;
this.rbWithdrawal.Text = "Withdrawal";
this.rbWithdrawal.UseVisualStyleBackColor = true;
//
// rbServFee
//
this.rbServFee.AutoSize = true;
this.rbServFee.Location = new System.Drawing.Point(481, 74);
this.rbServFee.Name = "rbServFee";
this.rbServFee.Size = new System.Drawing.Size(82, 17);
this.rbServFee.TabIndex = 5;
this.rbServFee.TabStop = true;
this.rbServFee.Text = "Service Fee";
this.rbServFee.UseVisualStyleBackColor = true;
//
// lblPayee
//
this.lblPayee.AutoSize = true;
this.lblPayee.Location = new System.Drawing.Point(12, 53);
this.lblPayee.Name = "lblPayee";
this.lblPayee.Size = new System.Drawing.Size(40, 13);
this.lblPayee.TabIndex = 0;
this.lblPayee.Text = "Payee:";
//
// txtPayee
//
this.txtPayee.Location = new System.Drawing.Point(15, 71);
this.txtPayee.Name = "txtPayee";
this.txtPayee.Size = new System.Drawing.Size(230, 20);
this.txtPayee.TabIndex = 6;
//
// lblCheckNum
//
this.lblCheckNum.AutoSize = true;
this.lblCheckNum.Location = new System.Drawing.Point(263, 53);
this.lblCheckNum.Name = "lblCheckNum";
this.lblCheckNum.Size = new System.Drawing.Size(81, 13);
this.lblCheckNum.TabIndex = 0;
this.lblCheckNum.Text = "Check Number:";
//
// txtCheckNum
//
this.txtCheckNum.Location = new System.Drawing.Point(266, 71);
this.txtCheckNum.Name = "txtCheckNum";
this.txtCheckNum.Size = new System.Drawing.Size(100, 20);
this.txtCheckNum.TabIndex = 7;
//
// lblCBalance
//
this.lblCBalance.AutoSize = true;
this.lblCBalance.Location = new System.Drawing.Point(12, 109);
this.lblCBalance.Name = "lblCBalance";
this.lblCBalance.Size = new System.Drawing.Size(86, 13);
this.lblCBalance.TabIndex = 0;
this.lblCBalance.Text = "Current Balance:";
//
// txtCBalance
//
this.txtCBalance.Location = new System.Drawing.Point(145, 102);
this.txtCBalance.Name = "txtCBalance";
this.txtCBalance.ReadOnly = true;
this.txtCBalance.Size = new System.Drawing.Size(100, 20);
this.txtCBalance.TabIndex = 0;
//
// lstTransactions
//
this.lstTransactions.FormattingEnabled = true;
this.lstTransactions.Location = new System.Drawing.Point(15, 125);
this.lstTransactions.Name = "lstTransactions";
this.lstTransactions.Size = new System.Drawing.Size(439, 316);
this.lstTransactions.TabIndex = 0;
//
// btnNewTran
//
this.btnNewTran.Location = new System.Drawing.Point(460, 171);
this.btnNewTran.Name = "btnNewTran";
this.btnNewTran.Size = new System.Drawing.Size(99, 23);
this.btnNewTran.TabIndex = 8;
this.btnNewTran.Text = "New Transaction";
this.btnNewTran.UseVisualStyleBackColor = true;
//
// btnRemTran
//
this.btnRemTran.Location = new System.Drawing.Point(460, 252);
this.btnRemTran.Name = "btnRemTran";
this.btnRemTran.Size = new System.Drawing.Size(99, 23);
this.btnRemTran.TabIndex = 9;
this.btnRemTran.Text = "Remove";
this.btnRemTran.UseVisualStyleBackColor = true;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(460, 333);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(99, 23);
this.btnClear.TabIndex = 10;
this.btnClear.Text = "Clear";
this.btnClear.UseVisualStyleBackColor = true;
//
// btnExit
//
this.btnExit.Location = new System.Drawing.Point(460, 414);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(99, 23);
this.btnExit.TabIndex = 11;
this.btnExit.Text = "Exit";
this.btnExit.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(578, 450);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnRemTran);
this.Controls.Add(this.btnNewTran);
this.Controls.Add(this.lstTransactions);
this.Controls.Add(this.txtCBalance);
this.Controls.Add(this.lblCBalance);
this.Controls.Add(this.txtCheckNum);
this.Controls.Add(this.lblCheckNum);
this.Controls.Add(this.txtPayee);
this.Controls.Add(this.lblPayee);
this.Controls.Add(this.rbServFee);
this.Controls.Add(this.rbWithdrawal);
this.Controls.Add(this.rbDeposit);
this.Controls.Add(this.lblTType);
this.Controls.Add(this.txtTAmount);
this.Controls.Add(this.lblTAmount);
this.Controls.Add(this.txtTDate);
this.Controls.Add(this.lblTDate);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblTDate;
private System.Windows.Forms.TextBox txtTDate;
private System.Windows.Forms.Label lblTAmount;
private System.Windows.Forms.TextBox txtTAmount;
private System.Windows.Forms.Label lblTType;
private System.Windows.Forms.RadioButton rbDeposit;
private System.Windows.Forms.RadioButton rbWithdrawal;
private System.Windows.Forms.RadioButton rbServFee;
private System.Windows.Forms.Label lblPayee;
private System.Windows.Forms.TextBox txtPayee;
private System.Windows.Forms.Label lblCheckNum;
private System.Windows.Forms.TextBox txtCheckNum;
private System.Windows.Forms.Label lblCBalance;
private System.Windows.Forms.TextBox txtCBalance;
private System.Windows.Forms.ListBox lstTransactions;
private System.Windows.Forms.Button btnNewTran;
private System.Windows.Forms.Button btnRemTran;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnExit;
}
}
I pretty much tried to use quick fixes and watched some random videos and came up with nothing.
Don't add your items to the ListBox directly. Create an appropriate list and bind that to the ListBox, then add your items to that list. If you use a BindingList<Transaction> then adding an item to the list will automatically update the bound control, which will not happen with a List<Transaction>.
var transactions = new BindingList<Transaction>();
myListBox.DataSource = transactions;
By default, when you add an item to a ListBox, ToString is called on that object and the result displayed. If you don't override the ToString method, that will just be the name of the type. You can set the DisplayMember of the ListBox and the specified property value will be displayed, e.g.
var transactions = new BindingList<Transaction>();
myListBox.DisplayMember = nameof(Transaction.Amount);
myListBox.DataSource = transactions;
Note that only properties can be specified as the DisplayMember or ValueMember. Fields will not work.
If you want some custom text displayed then you need to override the ToString method and have it return the desired text.

Bind List<class> to DataGridView

I need your help on how to bind List to the DataGridView. I tried to use the BindingList<T> but still it does not display the records in my gridview. I tried using the List<T>, but it still does not work.
Below is the code which I used:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ToolClientController ctrl = new ToolClientController();
IpAddressTextbox.Text = ctrl.GetIPv4Config();
PortNumberTextbox.Text = ctrl.GetPortNumber();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
ToolMsgFileTextbox.Text = openFileDialog1.FileName;
}
}
private void UploadButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(ToolMsgFileTextbox.Text))
{
FileTypeError.SetError(UploadButton, "Please enter filename.");
return;
}
if (!openFileDialog1.FileName.Contains(".txt"))
{
FileTypeError.SetError(UploadButton, "File should be in .txt");
return;
}
ToolClientController ctrl = new ToolClientController();
List<ToolMessages> test = new List<ToolMessages>();
ToolMessages tool = new ToolMessages();
tool.IsPass = true;
tool.ToolMessageReply = string.Empty;
tool.ToolMessageRequest = "x";
test.Add(tool);
MessageGridViews.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.DataPropertyName = "ToolMessageRequest";
col1.HeaderText = "Request";
MessageGridViews.Columns.Add(col1);
BindingList<ToolMessages> bind = new BindingList<ToolMessages>(test);
MessageGridViews.VirtualMode = true;
MessageGridViews.DataSource = bind;
}
}
Based on your code I prepared simple WinForms app:
public Form1()
{
InitializeComponent();
List<ToolMessages> test = new List<ToolMessages>();
ToolMessages tool = new ToolMessages();
tool.IsPass = true;
tool.ToolMessageReply = string.Empty;
tool.ToolMessageRequest = "x";
test.Add(tool);
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.DataPropertyName = "ToolMessageRequest";
col1.HeaderText = "Request";
dataGridView1.Columns.Add(col1);
BindingList<ToolMessages> bind = new BindingList<ToolMessages>(test);
dataGridView1.DataSource = bind;
dataGridView1.Show();
}
I added dataGridView1 into form directly via WinForms designer, so InitializeComponent method looks like:
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(560, 57);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(967, 399);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
And everything seems to work just fine... Data are bound to grid and ouput looks like:
which is exactly what I would expect to see, so I don't see any real problem with you solution, unless you post bigger piece of your code on which I can reproduce the issue you are experiencing.

Preventing users from resizing columns widths in ListView?

I have a ListView In My Winform that has 4columns, Name, Money, ID and Level.
The problem is when I run my app, I still have the ability to mess with the columns widths
and change them.
I searched And found that I should do something like this:
private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
e.Cancel = true;
e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
}
But the problem is that when I debugged and Ccanged the columns widths, this event didn't even fire!
Why didn't it fire?
And how can I make the column widths fixed?
I made a new winform app just in case if there was something wrong in my old one,
it fired, but only for the first time running the app .. here's the code:
namespace CsharpWinformTestingStuff
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listView1.ColumnWidthChanging += new ColumnWidthChangingEventHandler(listView1_ColumnWidthChanging);
}
void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
e.Cancel = true;
e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
}
}
}
here is the initialize component just in case you might wanna know:
private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.SuspendLayout();
//
// listView1
//
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.listView1.GridLines = true;
this.listView1.Location = new System.Drawing.Point(12, 12);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(284, 275);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Name";
this.columnHeader1.Width = 97;
//
// columnHeader2
//
this.columnHeader2.Text = "Age";
this.columnHeader2.Width = 52;
//
// columnHeader3
//
this.columnHeader3.Text = "Email";
this.columnHeader3.Width = 157;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(308, 299);
this.Controls.Add(this.listView1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
You need to register the ColumnWidthChanging event with your form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// This line registers the event, soc that the form can "hear" it and call the indicated handling code:
this.listView1.ColumnWidthChanging += new ColumnWidthChangingEventHandler(listView1_ColumnWidthChanging);
}
void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
Console.Write("Column Resizing");
e.NewWidth = this.listView1.Columns[e.ColumnIndex].Width;
e.Cancel = true;
}
}
Just click on the Properties>>Events>>ColumnWidthChanging.
Then add this code:
private void lstItems_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
e.Cancel = true;
e.NewWidth = lstItems.Columns[e.ColumnIndex].Width;
}
Happy coding! ^_^
You may check Better ListView Express. We have implemented AllowResize property on the columns, which does exactly what you need.

C# WinForms - how to send updates from DataGridView to DataBase

I have a .mdb file with a Customers table and an Agents table. The only thing that the Agents table does as yet is populate the Agent dropdown for each customer...
I have a DataGridView linked to the customerBindingSource. The customerBindingSource has DataMember set to Customer and DataSource set to bindingSource1. This has the DataSource set to customerAppDS21. If I select customerAppDS21 and click Edit in DataSet Designer I can quite clearly see that there is a Customer table and Agent table. These were dragged directly from the Data.mdf > Tables folder. I have been through the Configure wizard and checked that the Update, Insert and Delete commands are generated correctly.
I am setting the unique ID (GUID) when the user leaves a row or adds a row (I dont think both are needed, but I very much doubt this is the cause of the problem). The user can update or add as many rows as possible. When the user clicks the Save button it calls customerTableAdapter.Update(customerAppDS21.Customer);. All the events are definitely wired up correctly.
The problem is basically that the DataSet appears to get updated but the database itself is not updated. I can close the program and reload it straight away and the data is there. However if I make any changes to the code and then recompile and load the program all the data is gone. This is what makes me think the DataSet is being updated but not the database.
Does anyone have any idea how to solve the problem? I have tried adding the .acceptChanges(); line both before and after the .Update(bla); line, with no success. I have also tried calling customerBindingSource.EndEdit(); and bindingSource1.EndEdit(); before the .Update(bla); line.
Any help with this would be greatly appreciated. I have had this problem for 2 days now and tried alsorts of tutorials to get a hint on where I am going wrong.
Regards,
Richard
Update: Code below...
void button1_Click(object sender, EventArgs e)
{
Validate();
customerBindingSource.EndEdit();
customerTableAdapter.Update(customerAppDS21.Customer);
}
void grdCustomers_RowLeave(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow gvr = grdCustomers.Rows[e.RowIndex];
if (gvr.Cells[0].Value == null)
{
String g = Guid.NewGuid().ToString();
gvr.Cells[0].Value = g;
}
else
{
String currID = gvr.Cells[0].Value.ToString();
if (currID.Equals(""))
{
String g = Guid.NewGuid().ToString();
gvr.Cells[0].Value = g;
}
}
}
void grdCustomers_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
DataGridViewRow gvr = grdCustomers.Rows[grdCustomers.SelectedCells[0].RowIndex];
if (gvr.Cells[0].Value == null)
{
String g = Guid.NewGuid().ToString();
gvr.Cells[0].Value = g;
}
else
{
String currID = gvr.Cells[0].Value.ToString();
if (currID.Equals(""))
{
String g = Guid.NewGuid().ToString();
gvr.Cells[0].Value = g;
}
}
}
Designer code (sorry its so long - I dont want to risk missing out anything vital):
namespace CustomerApp
{
partial class CustomerAppForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.button1 = new System.Windows.Forms.Button();
this.grdCustomers = new System.Windows.Forms.DataGridView();
this.agentBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
this.customerAppDS21 = new CustomerApp.CustomerAppDS2();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.customerTableAdapter = new CustomerApp.CustomerAppDS2TableAdapters.CustomerTableAdapter();
this.agentTableAdapter = new CustomerApp.CustomerAppDS2TableAdapters.AgentTableAdapter();
this.customerBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.idDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companynameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.contactforenameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.contactsurnameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companyaddress1DataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companyaddress2DataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companytownDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companycountyDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.companypostcodeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.contacttelephoneDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.contactfaxDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.contactemailDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.agentIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.contactfullnameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdCustomers)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.agentBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.customerAppDS21)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.customerBindingSource)).BeginInit();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(12, 12);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1000, 640);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.button1);
this.tabPage1.Controls.Add(this.grdCustomers);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(992, 614);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Customers";
this.tabPage1.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(882, 462);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Save";
this.button1.UseVisualStyleBackColor = true;
//
// grdCustomers
//
this.grdCustomers.AllowUserToOrderColumns = true;
this.grdCustomers.AutoGenerateColumns = false;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.grdCustomers.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.grdCustomers.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdCustomers.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.idDataGridViewTextBoxColumn,
this.companynameDataGridViewTextBoxColumn,
this.contactforenameDataGridViewTextBoxColumn,
this.contactsurnameDataGridViewTextBoxColumn,
this.companyaddress1DataGridViewTextBoxColumn,
this.companyaddress2DataGridViewTextBoxColumn,
this.companytownDataGridViewTextBoxColumn,
this.companycountyDataGridViewTextBoxColumn,
this.companypostcodeDataGridViewTextBoxColumn,
this.contacttelephoneDataGridViewTextBoxColumn,
this.contactfaxDataGridViewTextBoxColumn,
this.contactemailDataGridViewTextBoxColumn,
this.agentIDDataGridViewTextBoxColumn,
this.contactfullnameDataGridViewTextBoxColumn});
this.grdCustomers.DataSource = this.customerBindingSource;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.grdCustomers.DefaultCellStyle = dataGridViewCellStyle2;
this.grdCustomers.Location = new System.Drawing.Point(3, 3);
this.grdCustomers.Name = "grdCustomers";
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.grdCustomers.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
this.grdCustomers.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.grdCustomers.RowTemplate.DefaultCellStyle.Padding = new System.Windows.Forms.Padding(2);
this.grdCustomers.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.grdCustomers.Size = new System.Drawing.Size(983, 605);
this.grdCustomers.TabIndex = 0;
//
// agentBindingSource
//
this.agentBindingSource.DataMember = "Agent";
this.agentBindingSource.DataSource = this.bindingSource1;
//
// bindingSource1
//
this.bindingSource1.AllowNew = true;
this.bindingSource1.DataSource = this.customerAppDS21;
this.bindingSource1.Position = 0;
//
// customerAppDS21
//
this.customerAppDS21.DataSetName = "CustomerAppDS2";
this.customerAppDS21.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// tabPage2
//
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(992, 614);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Agents";
this.tabPage2.UseVisualStyleBackColor = true;
//
// customerTableAdapter
//
this.customerTableAdapter.ClearBeforeFill = true;
//
// agentTableAdapter
//
this.agentTableAdapter.ClearBeforeFill = true;
//
// customerBindingSource
//
this.customerBindingSource.DataMember = "Customer";
this.customerBindingSource.DataSource = this.bindingSource1;
//
// idDataGridViewTextBoxColumn
//
this.idDataGridViewTextBoxColumn.DataPropertyName = "id";
this.idDataGridViewTextBoxColumn.HeaderText = "id";
this.idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";
this.idDataGridViewTextBoxColumn.ReadOnly = true;
//
// companynameDataGridViewTextBoxColumn
//
this.companynameDataGridViewTextBoxColumn.DataPropertyName = "company_name";
this.companynameDataGridViewTextBoxColumn.HeaderText = "Company Name";
this.companynameDataGridViewTextBoxColumn.Name = "companynameDataGridViewTextBoxColumn";
this.companynameDataGridViewTextBoxColumn.ToolTipText = "The name of the company";
//
// contactforenameDataGridViewTextBoxColumn
//
this.contactforenameDataGridViewTextBoxColumn.DataPropertyName = "contact_forename";
this.contactforenameDataGridViewTextBoxColumn.HeaderText = "Contact Forename";
this.contactforenameDataGridViewTextBoxColumn.Name = "contactforenameDataGridViewTextBoxColumn";
//
// contactsurnameDataGridViewTextBoxColumn
//
this.contactsurnameDataGridViewTextBoxColumn.DataPropertyName = "contact_surname";
this.contactsurnameDataGridViewTextBoxColumn.HeaderText = "Contact Surname";
this.contactsurnameDataGridViewTextBoxColumn.Name = "contactsurnameDataGridViewTextBoxColumn";
//
// companyaddress1DataGridViewTextBoxColumn
//
this.companyaddress1DataGridViewTextBoxColumn.DataPropertyName = "company_address1";
this.companyaddress1DataGridViewTextBoxColumn.HeaderText = "Address 1";
this.companyaddress1DataGridViewTextBoxColumn.Name = "companyaddress1DataGridViewTextBoxColumn";
//
// companyaddress2DataGridViewTextBoxColumn
//
this.companyaddress2DataGridViewTextBoxColumn.DataPropertyName = "company_address2";
this.companyaddress2DataGridViewTextBoxColumn.HeaderText = "Address 2";
this.companyaddress2DataGridViewTextBoxColumn.Name = "companyaddress2DataGridViewTextBoxColumn";
//
// companytownDataGridViewTextBoxColumn
//
this.companytownDataGridViewTextBoxColumn.DataPropertyName = "company_town";
this.companytownDataGridViewTextBoxColumn.HeaderText = "Town";
this.companytownDataGridViewTextBoxColumn.Name = "companytownDataGridViewTextBoxColumn";
//
// companycountyDataGridViewTextBoxColumn
//
this.companycountyDataGridViewTextBoxColumn.DataPropertyName = "company_county";
this.companycountyDataGridViewTextBoxColumn.HeaderText = "County";
this.companycountyDataGridViewTextBoxColumn.Name = "companycountyDataGridViewTextBoxColumn";
//
// companypostcodeDataGridViewTextBoxColumn
//
this.companypostcodeDataGridViewTextBoxColumn.DataPropertyName = "company_postcode";
this.companypostcodeDataGridViewTextBoxColumn.HeaderText = "Postcode";
this.companypostcodeDataGridViewTextBoxColumn.Name = "companypostcodeDataGridViewTextBoxColumn";
//
// contacttelephoneDataGridViewTextBoxColumn
//
this.contacttelephoneDataGridViewTextBoxColumn.DataPropertyName = "contact_telephone";
this.contacttelephoneDataGridViewTextBoxColumn.HeaderText = "Telephone";
this.contacttelephoneDataGridViewTextBoxColumn.Name = "contacttelephoneDataGridViewTextBoxColumn";
//
// contactfaxDataGridViewTextBoxColumn
//
this.contactfaxDataGridViewTextBoxColumn.DataPropertyName = "contact_fax";
this.contactfaxDataGridViewTextBoxColumn.HeaderText = "Fax";
this.contactfaxDataGridViewTextBoxColumn.Name = "contactfaxDataGridViewTextBoxColumn";
//
// contactemailDataGridViewTextBoxColumn
//
this.contactemailDataGridViewTextBoxColumn.DataPropertyName = "contact_email";
this.contactemailDataGridViewTextBoxColumn.HeaderText = "Email";
this.contactemailDataGridViewTextBoxColumn.Name = "contactemailDataGridViewTextBoxColumn";
//
// agentIDDataGridViewTextBoxColumn
//
this.agentIDDataGridViewTextBoxColumn.DataPropertyName = "agentID";
this.agentIDDataGridViewTextBoxColumn.DataSource = this.agentBindingSource;
this.agentIDDataGridViewTextBoxColumn.DisplayMember = "contact_fullname";
this.agentIDDataGridViewTextBoxColumn.HeaderText = "agentID";
this.agentIDDataGridViewTextBoxColumn.Name = "agentIDDataGridViewTextBoxColumn";
this.agentIDDataGridViewTextBoxColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.agentIDDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.agentIDDataGridViewTextBoxColumn.ValueMember = "id";
//
// contactfullnameDataGridViewTextBoxColumn
//
this.contactfullnameDataGridViewTextBoxColumn.DataPropertyName = "contact_fullname";
this.contactfullnameDataGridViewTextBoxColumn.HeaderText = "contact_fullname";
this.contactfullnameDataGridViewTextBoxColumn.Name = "contactfullnameDataGridViewTextBoxColumn";
this.contactfullnameDataGridViewTextBoxColumn.ReadOnly = true;
this.contactfullnameDataGridViewTextBoxColumn.Visible = false;
//
// CustomerAppForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1184, 662);
this.Controls.Add(this.tabControl1);
this.Location = new System.Drawing.Point(100, 100);
this.Name = "CustomerAppForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Heritage Art Papers Ltd - Customer Application";
this.Load += new System.EventHandler(this.CustomerAppForm_Load);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grdCustomers)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.agentBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.customerAppDS21)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.customerBindingSource)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.BindingSource bindingSource1;
private CustomerAppDS2 customerAppDS21;
private System.Windows.Forms.BindingSource agentBindingSource;
private CustomerAppDS2TableAdapters.CustomerTableAdapter customerTableAdapter;
private CustomerAppDS2TableAdapters.AgentTableAdapter agentTableAdapter;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.BindingSource customerBindingSource;
private System.Windows.Forms.DataGridViewTextBoxColumn idDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companynameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contactforenameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contactsurnameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companyaddress1DataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companyaddress2DataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companytownDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companycountyDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn companypostcodeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contacttelephoneDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contactfaxDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contactemailDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewComboBoxColumn agentIDDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn contactfullnameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridView grdCustomers;
}
}
I guess this might be your problem. Read these two articles very carefully. The first one contains a thread where in the second link (I gave below) is suggested.
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58794.aspx
and
http://msdn.microsoft.com/en-us/library/ms246989.aspx
In the first link, read the answer of: Kerry Moorman.
I guess these links might help:
http://msdn.microsoft.com/en-us/library/xzb1zw3x%28VS.80%29.aspx
and
http://www.c-sharpcorner.com/UploadFile/Ashish1/dataset02052006180740PM/dataset.aspx

What is the C# version of VB.NET's InputBox?

What is the C# version of VB.NET's InputBox?
Add a reference to Microsoft.VisualBasic, InputBox is in the Microsoft.VisualBasic.Interaction namespace:
using Microsoft.VisualBasic;
string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate);
Only the first argument for prompt is mandatory
Dynamic creation of a dialog box. You can customize to your taste.
Note there is no external dependency here except winform
private static DialogResult ShowInputDialog(ref string input)
{
System.Drawing.Size size = new System.Drawing.Size(200, 70);
Form inputBox = new Form();
inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
inputBox.ClientSize = size;
inputBox.Text = "Name";
System.Windows.Forms.TextBox textBox = new TextBox();
textBox.Size = new System.Drawing.Size(size.Width - 10, 23);
textBox.Location = new System.Drawing.Point(5, 5);
textBox.Text = input;
inputBox.Controls.Add(textBox);
Button okButton = new Button();
okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
okButton.Name = "okButton";
okButton.Size = new System.Drawing.Size(75, 23);
okButton.Text = "&OK";
okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);
inputBox.Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
cancelButton.Name = "cancelButton";
cancelButton.Size = new System.Drawing.Size(75, 23);
cancelButton.Text = "&Cancel";
cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);
inputBox.Controls.Add(cancelButton);
inputBox.AcceptButton = okButton;
inputBox.CancelButton = cancelButton;
DialogResult result = inputBox.ShowDialog();
input = textBox.Text;
return result;
}
usage
string input="hede";
ShowInputDialog(ref input);
To sum it up:
There is none in C#.
You can use the dialog from Visual Basic by adding a reference to Microsoft.VisualBasic:
In Solution Explorer right-click on the References folder.
Select Add Reference...
In the .NET tab (in newer Visual Studio verions - Assembly tab) - select Microsoft.VisualBasic
Click on OK
Then you can use the previously mentioned code:
string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", 0, 0);
Write your own InputBox.
Use someone else's.
That said, I suggest that you consider the need of an input box in the first place. Dialogs are not always the best way to do things and sometimes they do more harm than good - but that depends on the particular situation.
There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there.
But I would suggest to not use it. It is ugly and outdated IMO.
Returns the string the user entered; empty string if they hit Cancel:
public static String InputBox(String caption, String prompt, String defaultText)
{
String localInputText = defaultText;
if (InputQuery(caption, prompt, ref localInputText))
{
return localInputText;
}
else
{
return "";
}
}
Returns the String as a ref parameter, returning true if they hit OK, or false if they hit Cancel:
public static Boolean InputQuery(String caption, String prompt, ref String value)
{
Form form;
form = new Form();
form.AutoScaleMode = AutoScaleMode.Font;
form.Font = SystemFonts.IconTitleFont;
SizeF dialogUnits;
dialogUnits = form.AutoScaleDimensions;
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.Text = caption;
form.ClientSize = new Size(
Toolkit.MulDiv(180, dialogUnits.Width, 4),
Toolkit.MulDiv(63, dialogUnits.Height, 8));
form.StartPosition = FormStartPosition.CenterScreen;
System.Windows.Forms.Label lblPrompt;
lblPrompt = new System.Windows.Forms.Label();
lblPrompt.Parent = form;
lblPrompt.AutoSize = true;
lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);
lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);
lblPrompt.Text = prompt;
System.Windows.Forms.TextBox edInput;
edInput = new System.Windows.Forms.TextBox();
edInput.Parent = form;
edInput.Left = lblPrompt.Left;
edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);
edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);
edInput.Text = value;
edInput.SelectAll();
int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);
//Command buttons should be 50x14 dlus
Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);
System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();
bbOk.Parent = form;
bbOk.Text = "OK";
bbOk.DialogResult = DialogResult.OK;
form.AcceptButton = bbOk;
bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);
bbOk.Size = buttonSize;
System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();
bbCancel.Parent = form;
bbCancel.Text = "Cancel";
bbCancel.DialogResult = DialogResult.Cancel;
form.CancelButton = bbCancel;
bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);
bbCancel.Size = buttonSize;
if (form.ShowDialog() == DialogResult.OK)
{
value = edInput.Text;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Multiplies two 32-bit values and then divides the 64-bit result by a
/// third 32-bit value. The final result is rounded to the nearest integer.
/// </summary>
public static int MulDiv(int nNumber, int nNumerator, int nDenominator)
{
return (int)Math.Round((float)nNumber * nNumerator / nDenominator);
}
Note: Any code is released into the public domain. No attribution required.
Not only should you add Microsoft.VisualBasic to your reference list for the project, but also you should declare 'using Microsoft.VisualBasic;' so you just have to use 'Interaction.Inputbox("...")' instead of Microsoft.VisualBasic.Interaction.Inputbox
Add reference to Microsoft.VisualBasic and use this function:
string response = Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);
The last 2 number is an X/Y position to display the input dialog.
You mean InputBox? Just look in the Microsoft.VisualBasic namespace.
C# and VB.Net share a common library. If one language can use it, so can the other.
Without adding a reference to Microsoft.VisualBasic:
// "dynamic" requires reference to Microsoft.CSharp
Type tScriptControl = Type.GetTypeFromProgID("ScriptControl");
dynamic oSC = Activator.CreateInstance(tScriptControl);
oSC.Language = "VBScript";
string sFunc = #"Function InBox(prompt, title, default)
InBox = InputBox(prompt, title, default)
End Function
";
oSC.AddCode(sFunc);
dynamic Ret = oSC.Run("InBox", "メッセージ", "タイトル", "初期値");
See these for further information:
ScriptControl
MsgBox in JScript
Input and MsgBox in JScript
.NET 2.0:
string sFunc = #"Function InBox(prompt, title, default)
InBox = InputBox(prompt, title, default)
End Function
";
Type tScriptControl = Type.GetTypeFromProgID("ScriptControl");
object oSC = Activator.CreateInstance(tScriptControl);
// https://github.com/mono/mono/blob/master/mcs/class/corlib/System/MonoType.cs
// System.Reflection.PropertyInfo pi = tScriptControl.GetProperty("Language", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.IgnoreCase);
// pi.SetValue(oSC, "VBScript", null);
tScriptControl.InvokeMember("Language", System.Reflection.BindingFlags.SetProperty, null, oSC, new object[] { "VBScript" });
tScriptControl.InvokeMember("AddCode", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { sFunc });
object ret = tScriptControl.InvokeMember("Run", System.Reflection.BindingFlags.InvokeMethod, null, oSC, new object[] { "InBox", "メッセージ", "タイトル", "初期値" });
Console.WriteLine(ret);
I was able to achieve this by coding my own. I don't like extending into and relying on large library's for something rudimental.
Form and Designer:
public partial class InputBox
: Form
{
public String Input
{
get { return textInput.Text; }
}
public InputBox()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
private void InputBox_Load(object sender, EventArgs e)
{
this.ActiveControl = textInput;
}
public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)
{
InputBox inputBox = null;
DialogResult results = DialogResult.None;
using (inputBox = new InputBox() { Text = title })
{
inputBox.labelMessage.Text = message;
inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;
inputBox.labelInput.Text = inputTitle;
inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;
inputBox.Size = new Size(
inputBox.Width,
8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));
results = inputBox.ShowDialog();
inputValue = inputBox.Input;
}
return results;
}
void labelInput_TextChanged(object sender, System.EventArgs e)
{
}
}
partial class InputBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelMessage = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.labelInput = new System.Windows.Forms.Label();
this.textInput = new System.Windows.Forms.TextBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.SuspendLayout();
//
// labelMessage
//
this.labelMessage.AutoSize = true;
this.labelMessage.Location = new System.Drawing.Point(3, 0);
this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);
this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(50, 13);
this.labelMessage.TabIndex = 99;
this.labelMessage.Text = "Message";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(316, 126);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Cancel";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(235, 126);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "OK";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// labelInput
//
this.labelInput.AutoSize = true;
this.labelInput.Location = new System.Drawing.Point(3, 6);
this.labelInput.Name = "labelInput";
this.labelInput.Size = new System.Drawing.Size(31, 13);
this.labelInput.TabIndex = 99;
this.labelInput.Text = "Input";
this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);
//
// textInput
//
this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textInput.Location = new System.Drawing.Point(3, 3);
this.textInput.Name = "textInput";
this.textInput.Size = new System.Drawing.Size(243, 20);
this.textInput.TabIndex = 1;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.labelInput);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.textInput);
this.splitContainer1.Size = new System.Drawing.Size(379, 50);
this.splitContainer1.SplitterDistance = 126;
this.splitContainer1.TabIndex = 99;
//
// splitContainer2
//
this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer2.IsSplitterFixed = true;
this.splitContainer2.Location = new System.Drawing.Point(12, 12);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.labelMessage);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);
this.splitContainer2.Size = new System.Drawing.Size(379, 108);
this.splitContainer2.SplitterDistance = 54;
this.splitContainer2.TabIndex = 99;
//
// InputBox
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(403, 161);
this.Controls.Add(this.splitContainer2);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "InputBox";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Title";
this.TopMost = true;
this.Load += new System.EventHandler(this.InputBox_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label labelMessage;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label labelInput;
private System.Windows.Forms.TextBox textInput;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
}
Usage:
String output = "";
result = System.Windows.Forms.DialogResult.None;
result = InputBox.Show(
"Input Required",
"Please enter the value (if available) below.",
"Value",
out output);
if (result != System.Windows.Forms.DialogResult.OK)
{
return;
}
Note this exhibits a bit of auto sizing to keep it pretty based on how much text you ask it display. I also know it's lacking the bells and whistles but it's a solid step forward for those facing this same dilemma.
There is no such thing: I recommend to write it for yourself and use it whenever you need.

Categories

Resources