.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Post New Web Links

Remove a dynamically added ListViewItem from a ListView

Posted By:      Posted Date: September 07, 2010    Points: 0   Category :WPF
Good day, In my xaml I have created a window in my app which contains a  ListView control. I have programmatically added ListViewItems. The ListViewItems each contain a grid. Grid column 0 contains a textblock, Grid column 1 contains a textbox and Grid column 2 contains a button. What I would like to do is click the button in the ListViewItems grid, and remove the ListViewItem in the button is contained from the ListView. Could anyone suggest a way to do this? I would really appreciate any advice, as this is crucial to the feature I am creating.

View Complete Post

More Related Resource Links

Dynamically remove WPF contextmenu subitems?

Hi, How can I remove an item that is a subitem of a menu item? Snippet Snippet< UserControl.ContextMenu >          < ContextMenu  Name = "ContextMenu"  >              < MenuItem  Name = "Copy"  Header = "Copy"  Click = "Copy_Click"  InputGestureText = "Ctrl+C" />              < MenuItem  Header = "Cut"  Click = "Cut_Click"  InputGestureText = "Ctrl+X" />              < MenuItem  Header = "Paste"  Click = "Paste_Click"  InputGestureText = "Ctrl+V" />              < MenuItem  Name = "SendToItem"  Header = "Send To" >                  < MenuItem   Name = "RemoveItem"  Header = "REMOVE"  Click = "CopyToTac_Click" />   <!-- Add only to UH-1N -->       &nb

C# WPF ListView: ListViewItem content will not update?

I am having a problem updating a listview item which I have bindings set. Here is my XAML code and behind code. Also, the DownloadProgress and DownloadSize do not update but when I debug I see the changes made under the DownloadProgressChanged delegate: mtitem.dlbtn.MouseLeftButtonUp += delegate { MTDLItem dlitem = new MTDLItem(); dlitem.DownloadName = mtitem.tbmusicname.Text; dlitem.DownloadProgress = 0; dlitem.DownloadSize = ""; WebClient wc = new WebClient(); Uri webaddress = new Uri(mtitem.MusicLink); if (mtitem.Group == "5") { } else { string songtitle = mtitem.tbmusicname.Text + @".mp3"; string fixtitle = songtitle.Replace("\\", ""); if (Properties.Settings.Default.CopyRightMessage == false) { if (System.Windows.Forms.MessageBox.Show("GINtech Systems is not responsible for user applications of copyrighted music which may be in violation of existing local, state, or federal laws.", "MusicTuner Disclaimer", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Exclamation) == System.Windows.F

Remove Empty Listview Header

Can any one help me to remove the empty header generated at the end of a listview . i am using it to display a gridview of rows.

Display ListView inside ListViewItem???

Hi,   I was first using a tree view in order to display a two level hierarchical structure, however this was too slow (tree was taking up to 10 sec to display 3000 items). I believe that a listview will improve this performance. Is it possible to have a listview inside the listviewitem? So far I have this, the first level is being displayed, but no the second level Please help!! <ListBox x:Name="lstBoxHitList" Padding="5" Margin="1" ItemsSource="{x:Static local:Window1.SearchJobsList}" DockPanel.Dock="Bottom" MouseDoubleClick="tvHitList_MouseDoubleClick" TreeViewItem.Selected="tvHitList_Selected" ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ListBox.Resources> <Style TargetType="ListBox" x:Key="ListBoxControlStyle" BasedOn="{StaticResource {x:Type ListBox}}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Items.Count}" Value="0"> <Setter Property="Template"> <Setter.Value> <ControlTemplate>

how to generate a Serial number dynamically in listview



my listview having 3 columns:SI.No,HallticketNo,Name.

I bind data to listview but the "SI.No" column in listview showing Empty data.

So,how to generate serial number in listview ?

pls tell me very urgent.

Many thanks in advance.

WPF: how to make the listview work (apply basic listviewitem style and also apply special data


 We have defined the basic ListViewIItemStyle as following:

<!--ItemContainerStyle with the Trigger for selection x:Key="ListViewItemStyle"-->
 <Style x:Key="ListViewItemStyle"
  TargetType="{x:Type ListViewItem}">
 <Setter Property="Background"
 Value="Transparent" />
 <Setter Property="HorizontalContentAlignment"
 Value="Center" />
 <Setter Property="VerticalContentAlignment"
 Value="Center" />
 <Setter Property="Foreground"
 Value="Black" />
 <Setter Property="Margin"
 Value="5,0,5,0" />
 <Setter Property="MinHeight"
 Value="40" />
 <Setter Property="Template">
 <ControlTemplate TargetType="{x:Type ListViewItem}">
 <Border x:Name="Bd"
 <GridViewRowPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
 <!--<ContentPresenter HorizontalAlignment="Left"
  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />-->

Dynamically added text boxes disappears after page refresh


Dim objDatabase As New database
        Dim objAdapter As SqlDataAdapter
        Dim objDataset As New DataSet
        Dim objAdapter1 As SqlDataAdapter
        Dim objDataset1 As New DataSet
        Dim objAdapter2 As SqlDataAdapter
        Dim objDataset2 As New DataSet

        objAdapter = New SqlDataAdapter("SELECT first_name + ' ' + last_name as [Name],father_mobile_no as [Father Mob No],mother_mobile_no as [Mother Mob No] FROM student_data WHERE class='" & cmb_class.SelectedValue & "' and division = '" & cmb_division.SelectedValue & "' and school_id='" & Session("school_id") & "'", objDatabase.con)
        objAdapter.Fill(objDataset, 0)
        If objDataset.Tables(0).Rows.Count > 0 Then

            Dim dt_table As DataTable

Formatting layout of dynamically added controls


Ihave the following code and would like to be able to control the layout of the textboxes and labels so they arent just in a long column. Right now everything works and controls are added, but they are added in 1 column which if you chose 32 from the dropdown the page becomes very long.. so would like to maybe wrap them across 3 columns so that each has at least 10 per column.


for (int i = 0; i < Convert.ToInt32(ddlNumCam.SelectedValue); i++)   
    TextBox txtCamera = new TextBox();   
    Label lblCam = new Label();   
    txtCamera.ID = "txtCam" + i;   
    lblCam.ID = "lblCam" + i;   
    lblCam.Text = "Camera # " + i;   
    pnlCameras.Controls.Add(new LiteralControl("<br />"));   


Dynamically Added Controls and Events


Hi All,

I have a custom control that is dynamically added to a web page based on a search/sort that the user runs.  This is triggered by a button, at which point the controls are created and data populated.  The display of this data is functional, however this custom control contains a button.  After reading up on the lifecycle of the page, I realized that everything associated with the dynamic control is lost after a postback, and that the event is not raised until page_load has occurred.  Therefore, my button that triggered the postback disappeared into the ether before the ASP .Net Engine looked at the event.  

My question is, is there a way to dynamically create this control and being able to access the events?  Even if I put the data in the ViewState, and reload the control each Page_Load, the event data will be gone right, because the 'sender' ceases to exist?  Is this approach I'm trying to take a dead end?  Thanks in advance.

Remove column from Listview


I'm binding a listview control to LinqDataSource and can't find a way to remove unnecessary columns.

Grab the clientid of a dynamically added control


Hi all,

I add CompareValidators dynamically in my code behind. I need to access these controls within javascript to see if they are active or not. Whats the best way to do this?

The button that calls this javascript is also added dynamically. I dont know how many validators I add and they are added via a loop. I add the name to a string which I pass into my JS function, so within JS I have access to all validators added. Heres my code behind which creates the validators:

CompareValidator CV = new CompareValidator();
CV.ID = "CV" + parameter.Name;
CV.Type = ValidationDataType.Date;
CV.Operator = ValidationCompareOperator.DataTypeCheck;
CV.ErrorMessage = "* Invalid date";
CV.Display = ValidatorDisplay.Dynamic;
CV.ControlToValidate = parameter.Name;
CV.ValidationGroup = "valGroup1";
CV.Style["font"] = "Arial";
CV.Style["color"] = "Red";
CV.Style["font-size"] = "10px";


if (validators != "")
validators += ":" + CV.ClientID;
validators = CV.UniqueID;


I then add my button passing in 'validators' string:

HtmlInputButton btn = new HtmlInputButton();
btn.Value = "Run Report";
btn.ID = "Ru

How to get value from dynamically added html input?


Hi everyone,

 I'm struggling with the Javascript problem and need some help. On my page, I have a Javascript function that allowed users to add a text input with different ID:

<script language="javascript" type="text/javascript">
        function addElement() {
            var ni = document.getElementById('myDiv');
            var numi = document.getElementById('theValue');
            var num = (document.getElementById('theValue').value - 1) + 2;
            numi.value = num;
            var newdiv = document.createElement('div');
            var divIdName = 'my' + num + 'Div';
            newdiv.setAttribute('id', divIdName);
            newdiv.innerHTML = '<b>Citation ' + num + ': </b><input type="text" id="citation' + num + '" size="100%" />';

How do I get these Javascript-generated input elements after the user submits the form? 

Thanks for help,



Nested ListView: Parent listview item auto selection on child ListViewitem select


how can i auto select paraten listview item on selecting child listview item?

ListView ItemContainerStyle="{StaticResource myStyle}" Name="lv_list" Margin="5" HorizontalContentAlignment="Stretch">

ObjectDataSource doesn't remove previously added Parameter



I use an objectdatasource programmatically to use a parameterless method when SearchWord variable is empty and a Search method with one parameter when SearchWord is not empty, the event I use is objectdatasource selecting so that I can adjust parameters conveniently, I have a problem here: I can add a new parameter and set its value but I can't remove a previously added parameter from objectdatasource selectparameters and an error raises because of this, this is the selecting method:

 Protected Sub objWebUploadLog_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) Handles objWebUploadLog.Selecting

        If SearchWord = "" Then
            If objWebUploadLog.SelectParameters("search") Is Nothing Then

            End If
            objWebUploadLog.SelectMethod = "GetWebUploadLogByUserID"
            objWebUploadLog.SelectCountMethod = "GetWebUploadLogCountByUserID"
            If objWebUploadLog.SelectParameters("search") Is Nothing Then
                Dim param As WebControls.Parameter = New WebControls.Parameter("search", TypeCode.String)

Code analysis complaint (CA2000: Dispose objects before losing scope) on dynamically added control


It appears as though CA2000 was added to the code analysis for VS2010.


We have a bunch of code that dynamically adds controls during the CreateChildControls method. On various control types, we're getting this CA2000 complaint. I changed a bunch of controls to use a Using statement. When doing this on a AjaxControlToolkit.AlwaysVisibleControlExtender control, it caused the control to always appear at the bottom of the page rather than staying always visible. In the base class of this control, I noticed that there is logic to do things differently during PreRender if dispose had previously been called.


What is the proper way to satisfy CA2000 on a control like this while adding the control dynamically during CreateChildControls?

This is how the code was when getting CA2000.

            Dim alwaysVisibleControlExtender As New AjaxControlToolkit.AlwaysVisibleControlExtender
            With alwaysVisibleControlExtender
                .ID = Me.ID & "AlwaysVisibleControlExtender"
                .TargetControlID = m_AccordionAlwaysVisiblePanel.ID
                .VerticalSide = AjaxControlToolkit.VerticalSide.Top
                .HorizontalSide = AjaxControlToolkit.HorizontalSide.Center

ListView items added but not showing up.


This is a windows form.

I have a list view and have added items to it, but they are not showing up.

The code seems to run in debugging mode but still i do not see any items.

The listview is in details mode.

      this.lstvRunDetail.Items[lstvRunDetail.Items.Count - 1].SubItems.Add("bb");
      this.lstvRunDetail.Items[lstvRunDetail.Items.Count - 1].SubItems.Add("cc");
      this.lstvRunDetail.Items[lstvRunDetail.Items.Count - 1].SubItems.Add("dd");
      this.lstvRunDetail.Items[lstvRunDetail.Items.Count - 1].SubItems.Add("ee");
      this.lstvRunDetail.Items[lstvRunDetail.Items.Count - 1].SubItems.Add("ff");

Any ideas?

Thank you


Dynamically added table rows disappear on return



I am adding table rows dynamically, after I return from a post back, these rows disappear.

Is there a way to preserve these rows and add them back on page load?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend