Setting label text in listview control in loggedin template - c#

I need to set a label text which is listview and the listview is in Logged in template.
I am unable to set the value of the label. Here is the below code.
ListView ListView1 = (ListView)LoginView.FindControl("ListView1");
for (int i = 0; i < ListView1.Controls.Count; i++)
{
Label someLabel = (Label)ListView1.Controls[i].FindControl("nItemsId");
if (someLabel != null)
someLabel.Text = dt.Rows.Count.ToString();
}

So I think you need to use ListView.ItemCreated Event to achieve this
protected void LV_ItemCreated(object sender, ListViewItemEventArgs e)
{
// Retrieve the current item.
ListViewItem item = e.Item;
// Verify if the item is a data item.
if (item.ItemType == ListViewItemType.DataItem)
{
Label someLabel = (Label)ListView1.Controls[i].FindControl("nItemsId");
if (someLabel != null)
someLabel.Text = dt.Rows.Count.ToString();
}
}
To use it change your markup to declared the eventHandler like this.
<asp:ListView OnItemCreated="LV_ItemCreated" />

Related

How to open a form by Clicking on a specific Row in a ListView

I am trying to open a new form by clicking on a row in a ListView and pass the NoteId that is listed in the specific Row to the new Form, can anyone help please?
Sorry if this is a silly question, but I have only been programming since last month and my research proved fruitless :(
private void populatingMainList()
{
List<Note> getAllNotes = GetAllNotes();
lstMain.Items.Clear();
for (int i = 0; i < getAllNotes.Count; i++)
{
lstMain.FullRowSelect = true;
string _note;
ListViewItem lvi = new ListViewItem(_note = getAllNotes[i].NoteComplete.ToString());
if (_note == "True")
{
lvi.Text = "";
lvi.Checked = true;
}
else
{
lvi.Text = "";
lvi.Checked = false;
}
lvi.SubItems.Add(getAllNotes[i].NoteTitle);
lvi.SubItems.Add(getAllNotes[i].NoteDot.ToString("dd-MM-yyyy"));
lvi.SubItems.Add(getAllNotes[i].NoteNote);
lvi.SubItems.Add(getAllNotes[i].NoteId.ToString());
lstMain.Items.Add(lvi);
}
}
private void lstMain_SelectedIndexChanged_1(object sender, EventArgs e)
{
//I believe that some sort of code that retrieve NoteId from the specific Row must be added here.
if (_list == true)
{
frmSticky StickyForm = new frmSticky(_currentUser, _noteid);
}
}
private void lstMain_SelectedIndexChanged_1(object sender, EventArgs e)
{
var lst = sender as ListView;
_noteid = lst.SelectedItems[0].SubItems[3];
if (_list == true)
{
frmSticky StickyForm = new frmSticky(_currentUser, _noteid);
}
}
You can use a contextmenustrip for your listview and then add a button on it with function to open the form you are trying to.
1.Find ContextMenuStrip and add it to your application from toolbox.
2.Add it to your listview as shown in the image below.
3.Select the contextmenu you added and create a new button by clicking on "Type here".
4.Double click that button on your contextmenu and write the code you want to execute when you click on that button on contextmenu from listview.

Property returns different value than what was set

I am working on a Visual Studio extension and my current goal is to set up a menu item in the Tools menu. When clicked on this menu item will open a WinForms window containing a ListView, 3 textboxes, and a button. The idea is when you click on one of the rows in the ListView the data from that row will be populated in the textboxes so that you can update it. If you click the button a new row is added and the textboxes are cleared. However, I'm having an issue with getting the index of the row that I've selected.
private int _index;
private void newSourceBtn_Click(object sender, EventArgs e)
{
// Add new row to the ListView
ListViewItem row = new ListViewItem();
row.SubItems.Add("new");
row.SubItems.Add(String.Empty);
row.SubItems.Add(String.Empty);
remoteSourceListView.Items.Add(row);
int index = remoteSourceListView.Items.Count - 1;
remoteSourceListView.Items[index].Selected = true;
newSourceAdded = true;
sourceNameTextBox.Clear();
sourceUrlTextBox.Clear();
}
public void SourceName_TextChanged(object sender, EventArgs e)
{
remoteSourceListView.Items[IndexSelected].SubItems[1].Text = sourceNameTextBox.Text;
}
public void SourceURL_TextChanged(object sender, EventArgs e)
{
string url = sourceUrlTextBox.Text;
if ((url.StartsWith("http")) || (url.StartsWith("https")) || (url.StartsWith("git")))
{
sourceBranchTextBox.Enabled = true;
}
remoteSourceListView.Items[IndexSelected].SubItems[2].Text = url;
}
public void SourceBranch_TextChanged(object sender, EventArgs e)
{
}
public void SourcesListView_SelectedIndexChanged(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection selectedRows = remoteSourceListView.SelectedItems;
foreach (ListViewItem row in selectedRows)
{
sourceNameTextBox.Text = row.SubItems[1].Text;
sourceUrlTextBox.Text = row.SubItems[2].Text;
IndexSelected = row.Index;
if (row.SubItems[3].Text != "")
{
sourceBranchTextBox.Enabled = true;
sourceBranchTextBox.Text = row.SubItems[3].Text;
}
}
}
public int IndexSelected
{
get { return _index; }
set { _index = value; }
}
This code shows the button click event which adds the new row to the ListView, the text changed events for each of the textboxes which updates the row in the ListView (sorta), and the selected index changed event for the ListView which is where I'm getting the index of the row that was just selected. While debugging, I noticed that when I click on a row I'm getting the correct index in the selected index changed event; however, when I call IndexSelected from either of the text changed events it is always giving me a different index.
Any suggestions?
From the code posted I can't find any reason that explain the behavior documented.
A possible reason could be the insertion/deletion of new/existing ListViewItem in a position before the saved RowIndex.
However another approach is possible. Instead of keeping the RowIndex you could try to set a global property to the ListViewItem selected and reuse this instance when you need to set its subitems.
In this way you avoid problems if the number of ListViewItems change and some item is inserted/removed before the saved RowIndex. However a safeguard against a null value should be provided.
private ListViewItem CurrentItemSelected {get;set;}
......
public void SourcesListView_SelectedIndexChanged(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection selectedRows = remoteSourceListView.SelectedItems;
foreach (ListViewItem row in selectedRows)
{
sourceNameTextBox.Text = row.SubItems[1].Text;
sourceUrlTextBox.Text = row.SubItems[2].Text;
CurrentItemSelected = row;
if (row.SubItems[3].Text != "")
{
sourceBranchTextBox.Enabled = true;
sourceBranchTextBox.Text = row.SubItems[3].Text;
}
}
}
public void SourceName_TextChanged(object sender, EventArgs e)
{
if(CurrentItemSelected != null)
CurrentItemSelected.SubItems[1].Text = sourceNameTextBox.Text;
}
However, I am a bit perplexed by your code. Do you have the property MultiSelect set to true? Because if it is set to false then your code doesn't need to loop.
public void SourcesListView_SelectedIndexChanged(object sender, EventArgs e)
{
if(remoteSourceListView.SelectedItems.Count > 0)
{
// With MultiSelect = false; there is only one selected item.
CurrentItemSelected = remoteSourceListView.SelectedItems[0];
sourceNameTextBox.Text = CurrentItemSelected.SubItems[1].Text;
sourceUrlTextBox.Text = CurrentItemSelected.SubItems[2].Text;
if (CurrentItemSelected.SubItems[3].Text != "")
{
sourceBranchTextBox.Enabled = true;
sourceBranchTextBox.Text = CurrentItemSelected.SubItems[3].Text;
}
}
}

How to find a control (textbox) that was created during rowCommand and get its value

I have added a GridView to my webform. I then bounded data to the gridview programatically, followed by adding a RowDataBound function so that I can have each cell, in the gridView selectable as such:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
string clickInfo = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
// Add events to each editable cell
for (int columnIndex = 3; columnIndex < e.Row.Cells.Count; columnIndex++)
{
// Add the column index as the event argument parameter
string jsClick = clickInfo.Insert(clickInfo.Length - 2, columnIndex.ToString());
// Add this javascript to the onclick Attribute of the cell
e.Row.Cells[columnIndex].Attributes["onclick"] = jsClick;
// Add a cursor style to the cells
e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
}
}
}
...So then what i wanted to do is that whenever a cell is selected, turn that cell red and add a textbox so i can enter a value.. Shown below
<Columns>
<asp:ButtonField CommandName="CellClick" Visible="false" ControlStyle- CssClass="redCell"></asp:ButtonField>
</Columns>
codebehind:
public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "CellClick")
{
//INDEX INFO
int selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
int selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
//TRIGGERS EVENT FOR SELECTED CELL
GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Attributes["style"] += "background-color:Red;";
TextBox scheduleBox = new TextBox();
scheduleBox.CssClass = "redCell";
scheduleBox.ID = "ActiveCell";
scheduleBox.Width = 35;
this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls.Add(scheduleBox);
scheduleBox.Focus();
//LABEL INDEX INFO
lblCell.Text = (selectedColumnIndex - 2).ToString();
//LABEL HEADER & ROW TITLES
lblStartTime.Text = GridView1.Rows[selectedRowIndex].Cells[1].Text;
}
} GridView1.DataBind();
}
what I want to do now is once I press enter, get the value that currently resides in the texbox that was created programmatically and for now just display that value on a messagebox or whateevr (what Im really going to do is update a database but first I just need to find out how to get that value)
<asp:Panel runat="server" DefaultButton="Button1">
<asp:Button ID="Button1" CssClass="ActiveCell" runat="server" Style="display: none" OnClick="Button1_Click1" /></asp:Panel>
and the function Im using is this:
protected void Button1_Click1(object sender, EventArgs e)
{
var schedule = FindControl("ActiveCell") as TextBox;
ScriptManager.RegisterStartupScript(this, typeof(Page),
"alert", "alert('VALUE GOES HERE FROM TEXTBOX');", true);
}
So now my question: How can i get the value from ScheduleBox?
If I understand your question correctly, you should be able to use:
<%=schedule.ClientID %>.value
I am admittedly not a javascript expert, so let me know if that helps.
also, is the
var schedule = FindControl("ActiveCell") as TextBox;
returning the textbox correctly?
EDIT: if that doesn't work, try
<%=ActiveCell.ClientID %>.value
Have you tried looking into the controls of the cell of the selected row?
To work around the lack of a selectedColumnIndex in the GridView, I had to change your "GridView1_RowCommand" event to replace one line (to set the ID) and add one more:
scheduleBox.ID = "ActiveCell_" + selectedRowIndex.ToString() + "_" + selectedColumnIndex.ToString();
scheduleBox.TextChanged += scheduleBox_TextChanged;
It would look something like this:
int selectedColumnIndex = 0;
int selectedRowIndex = 0;
string lastUserInputText = string.Empty;
public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "CellClick")
{
//INDEX INFO
selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
//TRIGGERS EVENT FOR SELECTED CELL
GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Attributes["style"] += "background-color:Red;";
TextBox scheduleBox = new TextBox();
scheduleBox.CssClass = "redCell";
//This formats the ID so its unique, and now the TextBox contains the row and colummn indexes:
scheduleBox.ID = "ActiveCell_" + selectedRowIndex.ToString() + "_" + selectedColumnIndex.ToString();
scheduleBox.TextChanged += scheduleBox_TextChanged;
scheduleBox.Width = 35;
this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls.Add(scheduleBox);
scheduleBox.Focus();
//LABEL INDEX INFO
lblCell.Text = (selectedColumnIndex - 2).ToString();
////LABEL HEADER & ROW TITLES
lblStartTime.Text = GridView1.Rows[selectedRowIndex].Cells[1].Text;
}
GridView1.DataBind();
}
//The following event gets the current index of the Row and the column where the user is changing the text
void scheduleBox_TextChanged(object sender, EventArgs e)
{
TextBox txtSelected = (TextBox)sender;
string[] selectedValues = txtSelected.ID.Split(new char[] { '_' });
selectedRowIndex = int.Parse(selectedValues[1]);
selectedColumnIndex = int.Parse(selectedValues[2]);
//you could also use it to get the text directly while the user is editing it:
lastUserInputText = txtSelected.Text;
}
//This gets the text for the selected row and column. But if you only have 1 column with a TextBox it would be easier to just use the column index constant instead of doing it dynamically. However, remember you already have this value in the "lastUserInputText" variable. If you use that the following code may not be necessary:
string GetTextFromSelectedRowTextBox()
{
string textBoxValue = string.Empty;
foreach (Control curControl in this.GridView1.Rows[selectedRowIndex].Cells[selectedColumnIndex].Controls)
{
if (curControl is TextBox)
{
TextBox txtScheduleBox = (TextBox)curControl;
textBoxValue = txtScheduleBox.Text;
break;
}
}
return textBoxValue;
}

change databound listbox to longlistselector

I have a Listbox which items can be open & view by following code...
private void AccountsList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var listBoxItem = AccountsList.ItemContainerGenerator.ContainerFromIndex(AccountsList.SelectedIndex) as ListBoxItem;
var txtBlk = FindVisualChildByType<TextBlock>(listBoxItem, "txtBlkAccountName");
xCa = txtBlk.Text;
NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", a.ToString(), "View"), UriKind.Relative));
}
&
T FindVisualChildByType<T>(DependencyObject element, String name) where T : class
{
if (element is T && (element as FrameworkElement).Name == name)
{
return element as T;
}
int childcount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < childcount; i++)
{
T childElement = FindVisualChildByType<T>(VisualTreeHelper.GetChild(element, i), name);
if (childElement != null)
{
return childElement;
}
}
return null;
}
now i am implementing longlistselector instead of the listbox.
Long List Selector shows all my items from database but i am having problem while opening an item from this list... i cant use SelectedIndex in this longlistselector PLEASE HELP...
I would suggest you change your workflow. Instead of listening to the Tap event, listen to the SelectionChanged event. From this event you can get the SelectedItem. The SelectItem is the object the Items are bound to.
Example: Your ItemsSource is List each item within the ListBox or LongListSelector is bound to an instance of MyObject. Your "txtBlkAccountName" TextBlock should have it's Text bound to the AccountNumber property of your MyObject class.
private void LongListSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var myObj = AccountsList.SelectedItem as MyObject;
if(myObj == null) return;
var accountNum = myObj.AccountNumber;
NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", accountNum, "View"), UriKind.Relative));
// set the selectedItem to null so the page can be navigated to again
// If the user taps the same item
AccountsList.SelectedItem = null;
}
To get the item tapped, place the Tap even inside the ItemTemplate not the List, then you can use the sender property to retrieve the value you want.
Also instead of using FindVisualChildByType to get the value you want you should be able to just use the DataContext to retrieve whatever you want:
private void AccountsItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
FrameworkElement element=sender as FrameworkElement ;
Account item= element.DataContext as Account ;
xCa = item.Name;
NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", a.ToString(), "View"), UriKind.Relative));
}

RadioButtons CheckedChanged event

I have 20 radiobuttons on the page and I want to know which one of them was clicked.
protected void Page_Load(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "Button 1";
PlaceHolder1.Controls.Add(newBTN);
for (int i = 0; i < 20; i++)
{
RadioButton r = new RadioButton();
r.ID = i.ToString();
r.CheckedChanged += RadioButton1_CheckedChanged;
PlaceHolder1.Controls.Add(r);
}
}
New Updated code.. NOTE: THE CODE DOESNT RELATE TO THE ABOVE CODE.
public List<int> ThreadID2Treat { get { return ViewState["Checked"] == null ? null : (List<int>)ViewState["Checked"]; } set { ViewState["Checked"] = value; } }
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
int threadID = int.Parse(rad.ID.ToString());
ThreadID2Treat.Add(threadID);
}
public void DeleteButton_Clicked(object sender, EventArgs e)
{
foreach (var item in ThreadID2Treat)
{
UsefulStaticMethods.DeleteThreads(item);
}
}
How do i find out?
var rad = (RadioButton)sendder;
Response.Write("RadioButton Id :" + rad.Id.ToString());
You could try the above.
Update :
To get all select radio buttons in PlaceHolder make sure the AutoPostBack is not set on the radio buttons. You dont need to add CheckChanged Event. "r.CheckedChanged += RadioButton1_CheckedChanged;" <= remove.
StringBuilder stringBuilder = new StringBuilder();
foreach (var control in placeHolder1.Controls)
{
var rad = control as RadioButton;
if (rad != null)
{
if (rad.Checked)
stringBuilder.AppendLine(String.Format("Radion Button Checked : {0}", rad.ID));
}
}
Response.Write(stringBuilder.ToString());
With the parameter sender you have a direct reference to the event-source control.
var rb = (RadioButton)sender;
If you want to trigger this event and the postback directly, you must set the RadioButton's AutoPostBack-Property to true.
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
RadioButton radioButton = (RadioButton)sender;
//Code to use radioButton's properties to do something useful.
// get the radio button by its ID
string id = radioButton.ID;
}
}
You can try this.
RadioButton r = sender as RadioButton;
Response.Write(r.Id);
Cast sender as RadioButton:
RadioButton r = sender as RadioButton;
if(r != null)
{
//Do stuff
}

Categories