how can i change the value in the list view by clicking on it
e.g if the value in that column is p and after clicking on that row it replaces only p with a.
it only changes one value and on clicking another row it gives:
InvalidArgument=Value of '0' is not valid for 'index'.
private void show_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem nlist = new ListViewItem();
nlist = show.SelectedItems[0];
if (nlist.SubItems[3].Text == "P")
{
nlist.SubItems[3].Text = "A";
}
else if (nlist.SubItems[3].Text == "A")
{
nlist.SubItems[3].Text = "P";
}
else { }
}
Use if statement inside of your SelectedIndexChanged and check whether there is any selected item or not
if(show.SelectedItems.Count > 0)
{
ListViewItem nlist = new ListViewItem();
nlist = show.SelectedItems[0];
...
}
Related
I have a TextBox that searches whatever I have in my ListView. I would like to have a ComboBox that will allow the user to “Show All”, “Show Match” and “Show Non Match” within the ListView depending on search criteria.
private void SearchBtn_Click(object sender, EventArgs e)
{
int count = 0, searchStartIndex = selectedIndexPos = 0;
// Clear previously selected indices
listView.SelectedIndices.Clear();
string target = searchTextBox.Text;
// Search for item with text from the search text box, including subItems, from searchStartIndex, not a prefixSearch
ListViewItem item = listView.FindItemWithText(target, true, searchStartIndex, false);
/*----------------------------------------------------------------------------------------------------*
* While the search results in an item found continue searching. *
*----------------------------------------------------------------------------------------------------*/
while (item != null)
{
count++;
// Update progressBar
progressBar.Value = (int)((float)searchStartIndex / listView.VirtualListSize * 100);
ListView.SelectedIndexCollection indexes = listView.SelectedIndices;
if (!indexes.Contains(item.Index))
{
listView.SelectedIndices.Add(item.Index);
}
/*----------------------------------------------------------------------------------------------------*
* Set the start index to the index after the last found, if valid start index search for next item.*
*----------------------------------------------------------------------------------------------------*/
if ((searchStartIndex = item.Index + 1) < listView.VirtualListSize)
{
item = listView.FindItemWithText(searchTextBox.Text, true, searchStartIndex, false);
// count++;
}
else
{
item = null;
}
}
if (listView.SelectedIndices.Count == 0)
{
MessageBox.Show("Find item with text \"" + searchTextBox.Text + "\" has no result.");
}
else
{
RefilterListView();
listView.EnsureVisible(listView.SelectedIndices[0]);
}
}
I would like to have my items in the 'ComboBox' to help filter my 'ListView'. The "Show All" should display all contents of 'ListView' along with item that was searched, the "Show Match" should show only the searched item removing everything else that doesn't match the search and "Show Non Match" should show all of the contents from 'ListView' that doesn't match the searched item.
I can't do it exactly in your case. But I hope I realize it. I mean this is just a solution. You can customize it for your case.
First of all, put a BindingSource on your Form and bind it to your data:
bindingSource1.DataSource = data;
Then bind your ListView(actually DataGridView) to the BindingSource:
dataGridView1.DataSource = bindingSource1;
And then define an enum like this:
public enum Something
{
ShowMatch = 1,
ShowNonMatch = 2
}
Now, put a ComboBox on your Form and add your options to it:
comboBox1.Items.Add("Show All");
comboBox1.Items.Add("ShowMatch");
comboBox1.Items.Add("ShowNonMatch");
comboBox1.SelectedIndex = 0;
After that, you can catch the selected item in SelectedIndexChanged:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
bindingSource1.Filter = null;
else
bindingSource1.Filter = $"Name = '{comboBox1.SelectedItem.ToString()}'";
}
I need to to use a checkboxlist because there is a unique case the user is allowed to select 3 items at the same time. Problem is that I can't even manage to get the single selection to work. I'm doing this is codebehind with an updatepanel to not refresh the page.
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
int count = 0;
int i = 0;
int maxObjects = cblCodeRequest.Items.Count;
string[] checkObjects = new string[maxObjects];
ListItem selectedItem = new ListItem();
foreach (ListItem item in cblCodeRequest.Items)
{
checkObjects[i] = item.Text;
i++;
}
foreach (ListItem item in cblCodeRequest.Items)
{
if (item.Selected)
{
count++;
selectedItem = item;
cblCodeRequest.ClearSelection();
}
foreach (ListItem itm in cblCodeRequest.Items)
{
if (item.Equals(selectedItem))
{
item.Selected = true;
}
}
}
}
I'm not sure how to proceed from here, i already save the selected item and clear the whole selection and then set it again but it doesn't do it, it just selects itself again after even if i click a different checkbox. I think my logic is messed up
Try this, Your foreach statements are not arranged correctly
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedItem = cblCodeRequest.Items[cblCodeRequest.SelectedIndex]
cblCodeRequest.ClearSelection();
int x = 0;
for(x; x<cblCodeRequest.Items.Count; x++)
{
if (cblCodeRequest.Items[x].Equals(selectedItem))
{
item.Selected = true;
}
}
}
Ok, I finally solved this problem. I had to dig through the problem with the debugger and follow the logic. I did this in jQuery so I can remove the update panel. If Anyone ever gets the same problem as me, this is the solution for you.
This allows you to use a checkboxlist like a radiobuttonlist but also allows you to check multiple checkboxes that belong to a special selection group.
$(function () {
$('[id*=cblCodeRequest] input').on('click', function () {
var checkboxlist = $('[id*=cblCodeRequest]'); // CheckBoxList
var checkboxArray = $('[id*=cblCodeRequest] input'); // CheckBoxList Items
var current = $(this); // Get Selected Checkbox
var label = $(current).next().text(); // Get CheckBox label name
// Uncheck every checkBox that don't match the unique multi selection combo
if (label != "Recâmbio" && label != "Série" && label != "Embalagem Alternativa") {
// Loop through checkboxArray and uncheck every item that does not meet the condition
$(checkboxArray).each(function (i) {
$(this).prop("checked", false);
});
// Check the selected item again
$(current).prop("checked", true);
} else {
// Get the current checkbox name
var chk = $(current).next().text();
// If the checkbox that matches the unique combo selection was click uncheck all invalid checkboxes that don't match
if (chk == "Série" || chk == "Recâmbio" || chk == "Embalagem Alternativa") {
// loop through the checkboxlist again
$(checkboxArray).each(function () {
// Get the looped item name
var ck = $(this).next().text();
// if checkbox does not belong to the unique combo selection, uncheck it
if (ck != "Recâmbio" && ck != "Série" && ck != "Embalagem Alternativa") {
$(this).prop("checked", false);
}
});
}
}
});
});
I am trying to get specific cell value so i can pass it in my method when i press the button but i get always null on both (and i know that is not null).
P.s: None row is selected because i made a loop to get all the rows. The variable "p" is getting correct the number of the rows that i have on the grid.
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
string itemcodeparam = item["ItemCode"].Text;//error null (4th cell)
int quantityparam = Convert.ToInt16(item.Cells[5].Text);//error null
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue,itemcodeparam,-quantityparam);
}
}
}
Finally i did it with this code
protected void PostRadButton_Click(object sender, EventArgs e)
{
int p;
if (DocStatTxtBox.Text == "2")
{
foreach (GridDataItem item in RadGrid1.Items)
{
p = item.RowIndex;
Label itemparam = (Label)item["ItemCode"].FindControl("ItemCodeLabel");
Label qparam = (Label)item["Quantity"].FindControl("QuantityLabel");
string itemcodeparam = itemparam.Text;
int quantityparam = Convert.ToInt16(qparam.Text);
Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue, itemcodeparam, -quantityparam);
}
}
}
I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}
You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.
Am trying to delete textboxes and labels while their names which have equal value from the selected items from the listbox. If i run this code only the first if statement is executed and removing only the label controls inside the table.
I must also mention that controls of the table are dynamically created.
private void pictureBox2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox2.SelectedItems.Count; i++)
{
foreach (Control t in table2.Controls)
{
if (t is Label && t.Text==listBox2.SelectedItem.ToString())
{
table2.Controls.Remove(t);
continue;
}
if (t is TextBox && t.Name.Contains(listBox2.SelectedItem.ToString()))
{
table2.Controls.Remove(t); continue;
}
}
listBox2.Items.Remove(listBox2.SelectedItems[i]); i--;
}
}
This is how controls are created indide the table.
private void pictureBox1_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
this.table2.Controls.Clear();
foreach (var item in listBox1.SelectedItems)
{
table2.Controls.Add(new Label() { Name = item.ToString(), Text = item.ToString(), AutoSize = true });
table2.Controls.Add(new TextBox() { Name = item.ToString(), AutoSize = true });
}
}
}
When you remove an item from a collection (suppose the item at position 0), the item at the next position (postion 1) shifts in position zero. But your for loop execute the next iteration and your indexer becomes 1 and so it terminate the loop.
The first approach to avoid this is to loop in reverse order, from the end of the collection toward the begin of it
But you could also simplify a lot your code with
private void pictureBox2_Click(object sender, EventArgs e)
{
for (int i = listBox2.SelectedItems.Count - 1 ; i >= 0 ; i--)
{
// This is our search term...
string curItem = listBox2.SelectedItems[i].ToString();
// Get only the controls of type Label with Text property equal to the current item
var labels = table2.Controls
.OfType<Label>()
.Where (c => c.Text == curItem)
.ToList();
if(labels != null)
{
for(int x = labels.Count()-1; x >= 0; x--)
table2.Remove(labels[x]);
}
// Get only the controls of type TextBox with Name property containing the current item
var boxes = table2.Controls
.OfType<TextBox>()
.Where (c => c.Name.Contains(curItem)
.ToList();
if(boxes != null)
{
for(int x = boxes.Count()-1; x >= 0; x--)
table2.Remove(boxes[x]);
}
listBox2.Items.Remove(curItem);
}
}
Why are you decrementing your iterator at the end of your for loop? It looks like you're stuck in the loop, buddy.