ListView selectedindexchanged - c#

I need help to get a response when I click on an "Item" from a list view. Know that there is selectedindexchanged, but when I try to display a MessageBox so nothing happens, have tried lots of other things but have not managed to come up with something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
while (reader.Read())
{
string alio = reader["fornamn"].ToString();
string efternamn = reader["efternamn"].ToString();
ListViewItem lvi = new ListViewItem(alio);
listView1.Items.Add(lvi);
lvi.SubItems.Add(efternamn);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}

Assuming that 81.private void listView1_SelectedIndexChanged is properly linked to the listview, you will need to query the listview to find out what's selected:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.listView1.SelectedItems.Count == 0)
return;
string namn = this.listView1.SelectedItems[0].Text;
// Create the sql statement to retrieve details for the user
string sql = string.Format("select * from kunder where fornamn = '{0}', namn);
// do the same as you do to create a reader and update the controls.
}

Going by the term "when I try to display a MessageBox so nothing happens"\, I assume that you simply put MessageBox.Show("blah"); inside the event handler and never got it shown.
If that's the case, your event handler is not hooked properly to your form's list view. go back and see the text listView1_SelectedIndexChanged is anywhere to be found inside your Form1.Designer.cs file.
If not (or anyway), start over on a new form. That's the easiest way out. :)

private void lstView_KQ_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstView_KQ.SelectedItems.Count > 0)
{
ListViewItem itiem = stView_KQ.SelectedItems[lstView_KQ.SelectedItems.Count - 1];
if (itiem != null)
foreach (ListViewItem lv in lstView_KQ.SelectedItems)
{
txtMaNV.Text = lv.SubItems[0].Text;
cmbCV.Text = lv.SubItems[1].Text;
txtHoNV.Text = lv.SubItems[2].Text;
txtTenNV.Text = lv.SubItems[3].Text;
txtNgaysinh.Text = lv.SubItems[4].Text;
txtGioiTinh.Text = lv.SubItems[5].Text;
txtDiaChi.Text = lv.SubItems[6].Text;
txtSDT.Text = lv.SubItems[7].Text;
txtCMND.Text = lv.SubItems[8].Text;
}
}
}

Related

DataGridView not loading data programmatically

I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)

How to update datagridview based off of combo box selection?

I am attempting to write code that will display data in a datagridview based off of the size of car selected in a combo box. When this code initially runs, it defaults to economy sized, and displays the correct information in the datagridview. However, when a different size is selected in the combo box, the text boxes update correctly while the datagridview remains the same. What can I do to make it update every time the combo box is changed? I thought the code in "private void cboSize_selectionChangeCommitted()" would accomplish this, but there was no change in the output.
namespace carForm
{
public partial class Form1 : Form
{
_Cars_1_DataSet cDataSet;
BindingSource sizeBindingSource;
BindingSource vehicleBindingSource;
CarsDataClass clsCarsData;
Boolean gridInitialized;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the '_Cars_1_DataSet.Reservations' table. You can move, or remove it, as needed.
this.reservationsTableAdapter.Fill(this._Cars_1_DataSet.Reservations);
// TODO: This line of code loads data into the '_Cars_1_DataSet.Vehicle' table. You can move, or remove it, as needed.
this.vehicleTableAdapter.Fill(this._Cars_1_DataSet.Vehicle);
// TODO: This line of code loads data into the '_Cars_1_DataSet.CarSize' table. You can move, or remove it, as needed.
this.carSizeTableAdapter.Fill(this._Cars_1_DataSet.CarSize);
clsCarsData = new CarsDataClass();
cDataSet = clsCarsData.GetDataSet();
//Binding source sizes
sizeBindingSource = new BindingSource();
sizeBindingSource.DataSource = cDataSet;
sizeBindingSource.DataMember = "CarSize";
//Binding source vehicles
vehicleBindingSource = new BindingSource();
vehicleBindingSource.DataSource = cDataSet;
vehicleBindingSource.DataMember = "Vehicle";
//Combo box
cboSize.DataSource = sizeBindingSource;
cboSize.DisplayMember = "Size";
cboSize.ValueMember = "SizeCode";
//bind other controls
txtDaily.DataBindings.Add("text", sizeBindingSource, "DailyRate");
txtMileage.DataBindings.Add("text", sizeBindingSource, "MileageRate");
//execute combo box
cboSize_SelectionChangeCommitted(cboSize, e);
}
private void cboSize_SelectionChangeCommitted(object sender, EventArgs e)
{
string carSelected;
carSelected = Convert.ToString(cboSize.SelectedValue);
if (!gridInitialized)
{
dgvVehicles.DataSource = vehicleBindingSource;
gridInitialized = true;
ChangeGridColumns();
}
vehicleBindingSource.Filter = "CarSize = '" + carSelected + "'";
}
private void ChangeGridColumns()
{
//Change column headers
//dgvVehicles.Columns["Inv_ID"].Visible = false;
}
}
}
Try using SelectedIndexChanged event from the events menu after clicking on the combobox in the design view.
This should populate in your code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine("test!");
}
In there you can put this logic from your code:
string carSelected;
carSelected = Convert.ToString(cboSize.SelectedValue);
if (!gridInitialized)
{
dgvVehicles.DataSource = vehicleBindingSource;
gridInitialized = true;
ChangeGridColumns();
}
vehicleBindingSource.Filter = "CarSize = '" + carSelected + "'";
Use SelectedIndexChanged instead of SelectionChangeCommitted.

DataGridView Does not refresh after editing in c#

I have a data grid view whose data source gets assigned a list of items after the following function on load:
public void refreshGrid(object sender, FormClosingEventArgs e)
{
dgvItems.SuspendLayout();
itemBindingSource.SuspendBinding();
List<Item> items = db.Items.ToList(); // db is MyContext db = new MyContext();
itemBindingSource.DataSource = items;
dgvItems.DataSource = null;
dgvItems.DataSource = itemBindingSource;
itemBindingSource.ResumeBinding();
dgvItems.ResumeLayout();
}
private void AllItemsForm_Load(object sender, EventArgs e)
{
refreshGrid();
}
and there is a edit button which does the following on click:
private void btnEditItem_Click(object sender, EventArgs e)
{
Item item = (Item)dgvItems.SelectedRows[0].DataBoundItem;
var editForm = new EditItemForm(item);
editForm.FormClosing += new FormClosingEventHandler(refreshGrid);
editForm.Show();
}
i.e. opens an edit form and assigns refreshGrid() to its closing event.
On that Edit Form I have this Save button which does this:
private void btnSave_Click(object sender, EventArgs e)
{
Item itemEdited = db.Items.Where(i => i.itemId == itemEditing.itemId).Single();
itemEdited.categoryId = (int)cbxCategory.SelectedValue;
itemEdited.description = tbxDescription.Text;
itemEdited.price = (Double)nudPrice.Value;
db.Entry(itemEdited).State = EntityState.Modified;
db.SaveChanges();
this.Close();
}
the item edit is working, but is apparent only after closing and reopening the edit form, i.e. that refreshGrid() method which was assigned to its closing event is not working!
How can I fix this?
I found my own mistake. The mistake was using two different instances of Context class.
The solution was to add:
SomsaContext database = new SomsaContext(); // i.e. new instance of Context class
right before the refresh takes place.

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.

Calling an SQL stored procedure that's defined in a method using button click on form c#

Having a lot of trouble with this. I'm working on a large project, so there's only a few classes I'm interested in and working on. Basically, these are forms - one is a main editor where a user edits details and the other is used to assign a pin number. In the main editor form, if the user has a pin, they can choose to edit this pin. Here's where my problem lies - if I edit the pin, what I'm doing in the code is deleting the old pin and adding the new one. However, the database doesn't update until AFTER the editor form is closed. Therefore, I'd like to call the method that does change the database on the OKButton click, if I could. The problem I'm facing is I don't know how.
Here is the DB code, we'll say the class is called DetailsConn:
public string editPin(int driverID)
{
if (SchemaChecker.PINAvailable())
{
string sql = "EditPIN";
using (SqlCommand cmd = new SqlCommand(sql, base.connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Remove("#nDriverID");
cmd.Parameters.AddWithValue("#nDriverID", driverID);
cmd.Parameters.Remove("#nPIN");
SqlParameter pinParameter = cmd.Parameters.Add("#nPIN", SqlDbType.Char);
pinParameter.Direction = ParameterDirection.Output;
pinParameter.Size = 32;
cmd.ExecuteNonQuery();
return pinParameter.Value.ToString();
}
}
return "";
}
Here's the code for my edit:
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.listViewDriverTags.SelectedItems.Count > 0)
{
ListViewItem lvi = this.listViewDriverTags.SelectedItems[0];
DriverTag driverTag = lvi.Tag as DriverTag;
else if (blahTag.blahType == 2)
{
buttonAssignPIN_Click(sender, e);
}
//message stuff and dialog boxes with localization info
if (dr == DialogResult.Yes)
{
this.listViewDriverTags.Items.Remove(lvi);
if (Tag.id != -1)
{
TagsToBeDeleted.Add(driverTag);
}
}
if (dr == DialogResult.No)
{
this.listViewTags.Items.Clear();
this.listViewTags.Items.Add(lvi);
}
}
}
Here's my buttonAssignPIN stuff:
private void buttonAssignPIN_Click(object sender, EventArgs e)
{
using (AssignPINForm form = new AssignPINForm())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
DriverTag PIN = DriverTag.GetNewPIN(form.DriverTag);
ListViewItem lvi = this.listViewTags.Items.Add(PIN.driverTag);
lvi.SubItems.Add(this.TagTypes[PIN.TagType]);
lvi.Tag = PIN;
}
}
}
And finally, here's my AssignPINForm code:
public partial class AssignPINForm : Form
{
public AssignPINForm()
{
InitializeComponent();
this.buttonOK.Click += new EventHandler(buttonOK_Click);
this.buttonCancel.Click += new EventHandler(buttonCancel_Click);
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"^[0-9]{4,20}$";
Regex regex = new Regex(pattern);
buttonOK.Enabled = regex.IsMatch(textBoxPin.Text);
};
LoadStrings();
}
public void LoadStrings()
{
//stome stuff
}
public string DriverTag
{
get { return this.textBoxPin.Text; }
set { this.textBoxPin.Text = value; }
}
private void buttonOK_Click(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void AssignPINForm_Load(object sender, EventArgs e)
{
}
}
I know it's kind of all over the place but I've provided everything I think is relevant. The middle two snippets are in the same class too, and the DB stuff is the same solution but a different project. I'd be grateful if someone can decipher what I'm after and help me out, it's the only thing I have left to do on this particular bit!
Thanks!
Not sure I fully got what you're after and I agree with some of the comments that this isn't the best of practice but I guess what you're after is to update the buttonOK_Click method to something like this:
private void buttonOK_Click(object sender, EventArgs e)
{
using(DetailsConn connection = new DetailsConn())
{
int driver = -1;
if(int.TryParse(this.DriverTag, out driver)) {
connection.editPin(driver);
}
}
}
Also, you may want to remove any other possible references to the editPin() function.
I actually figured out that even if I got that working correctly, it wasn't going to solve my problem. I've had to call a new procedure and declare that in the database schema - basically it was a lot more complicated than what I was giving it credit for. Thanks for the responses nonetheless.

Categories