asp.net - How to use LinkButton click event

Click event in LinkButton control
LinkButton is an ASP.NET web server control. The LinkButton server control renders a hyperlink-style button control on the web page. Though it looks like a hyperlink it has the same functionality as a Button control. By default, a LinkButton control is a submit Button. We also can use it as a command button.

When we use LinkButton control as a regular submit button, we can provide an event handler for its Click event. Submit button simply posts the web page back to the server. This Click event allows us to programmatically control the action performed the submit Button (LinkButton) is clicked.

The LinkButton Click event occurs when the LinkButton control is clicked. The click event is commonly used when no command name is associated with the LinkButton control.

The LinkButton OnClick method raises the Click event of the LinkButton control. The OnClick method required a parameter named e. this parameter type is System.EventArgs that contains the event data.

The following ASP.NET C# example code demonstrates to us how can we use LinkButton click event in an ASP.NET application.
LinkButtonOnClick.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void LinkButton1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = "Your Address:<br />" + TextBox1.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use OnClick event in LinkButton control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">LinkButton Example: OnClick Event</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="HotPink"
             Font-Italic="true"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             Text="Address"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="LightGoldenrodYellow"
             ForeColor="DodgerBlue"
             TextMode="MultiLine"
             >
        </asp:TextBox>
        <br /><br />
        <asp:LinkButton 
             ID="LinkButton1" 
             runat="server"
             Text="Submit Address"
             OnClick="LinkButton1_Click"
             ForeColor="Crimson"
             Font-Size="Large"
             BorderWidth="2"
             >
        </asp:LinkButton>
    </div>
    </form>
</body>
</html>

asp.net - How to submit a form with a LinkButton

Submit an asp.net page by LinkButton control
LinkButton is an ASP.NET web server control. LinkButton control display as a hyperlink-style Button control on the web page. LinkButton server control has the same appearance as a hyperlink control but it has the same functionality as a regular button control. We can render LinkButton control as a Submit button or as a Command button on the web page. So we can submit an ASP.NET page to the web server by LinkButton control.

Submit button does not have a command name associated with it. By default, LinkButton control is a submit Button that simply posts the web page back to the server. We can provide an event handler for the LinkButton Click event to programmatically control the action performed when the submit Button is clicked. The LinkButton Click event occurs when the LinkButton control is clicked.

The following ASP.NET C# example code demonstrates to us how can we submit an ASP.NET page to the web server using LinkButton server control in an ASP.NET application. In this example, we created a LinkButton as a submit Button and we post the page to the web server when someone clicks the LinkButton control. After clicking the LinkButton, the web page displays user-submitted information on the web browser.
LinkButtonSubmit.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void LinkButton1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = "Hi " + TextBox1.Text;
        Label1.Text += "!<br />You are a " + RadioButtonList1.SelectedItem.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to submit asp.net page by LinkButton control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">LinkButton Example: Submit Page</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="SeaGreen"
             Font-Italic="true"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server"
             Font-Bold="true"
             ForeColor="HotPink"
             Text="Name"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="LightGoldenrodYellow"
             ForeColor="HotPink"
             >
        </asp:TextBox>
        <br /><br />
        <asp:RadioButtonList 
             ID="RadioButtonList1"
             runat="server"
             BorderWidth="2"
             BorderColor="Crimson"
             ForeColor="HotPink"
             RepeatColumns="2"
             Font-Bold="true"
             >
             <asp:ListItem>Boy</asp:ListItem>
             <asp:ListItem>Girl</asp:ListItem>
        </asp:RadioButtonList>
        <br /><br />
        <asp:LinkButton 
             ID="LinkButton1" 
             runat="server"
             Text="Submit Details"
             OnClick="LinkButton1_Click"
             ForeColor="SeaGreen"
             Font-Size="Large"
             BorderWidth="2"
             >
        </asp:LinkButton>
    </div>
    </form>
</body>
</html>

asp.net - How to change Label width programmatically

Change Label width programmatically
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can programmatically change a Label control’s width. Here we used the Label web server control’s Width property to change its width programmatically.

The Label control Width property gets or sets the width of the Web server control. The Width property value is a Unit that represents the width of the Label control. The default value of this property is Empty. The Unit structure represents a length measurement.

The Label control’s Width property throws ArgumentException if the width of the Web server control was set to a negative value. So finally, the asp.net c# developers can use the Width property to change the width of the Label Web server control programmatically.
LabelWidth.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Width = 75;
    }
    protected void Button2_Click(object sender, System.EventArgs e)
    {
        Label1.Width = 250;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to set, change Label width programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">Label Example: Width</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Text="Change Label Width."
             BackColor="SaddleBrown"
             ForeColor="Snow"
             BorderWidth="3"
             BorderColor="DodgerBlue"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             ForeColor="SaddleBrown"
             Text="Label Width 75"
             OnClick="Button1_Click"
             Font-Bold="true"
             />
        <asp:Button 
             ID="Button2" 
             runat="server" 
             Font-Bold="true"
             ForeColor="SaddleBrown"
             Text="Label Width 250"
             OnClick="Button2_Click"
             />
    </div>
    </form>
</body>
</html>

asp.net - How to change Label text programmatically

Change Label text programmatically
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can programmatically change a Label control’s text. Here we used the Label web server control’s Text property to change its contained text programmatically.

The Label control Text property gets or sets the text content of the Label control. This property value is a String which is the text content of the control. The default value of this property is Empty.

The asp.net developers have to use the Text property to specify or determine the text content of the Label control. The Label control’s Text property is commonly used to programmatically customize the text that is displayed in the Label control.

The Text property can include HTML but the HTML will be passed unchanged to the browser. If the asp.net developers want the browser to display HTML markup as plain text, they can use the HtmlEncode method.
LabelText.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = "You clicked the Button";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to set, change Label text programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">Label Example: Text</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Text="Click button for change This text."
             ForeColor="Crimson"
             BackColor="LightPink"
             Font-Size="X-Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             ForeColor="IndianRed"
             Text="Change Label Text"
             OnClick="Button1_Click"
             Font-Bold="true"
             />
    </div>
    </form>
</body>
</html>

asp.net - How to use associated control id in Label

AssociatedControlID in Label Server Control
The Label is an ASP.NET web server control that displays text on the web page. Label control’s AssociatedControlID property gets or sets the identifier for a server control that the Label control is associated with.

The AssociatedControlID property value type is a String. This String represents the ID of server control in the web form. The default value of this property is an empty String which means the Label server control is not associated with any other server control.

By using this property we can extend the functionality of the associated control. We can use the Label control as a caption for other control or we can set the tab index or hotkey for associated server control.

We can set the Label AccessKey property to provide the hotkey for associated control. We also can use the Label Text property to set a caption for associated server control.

The following ASP.NET C# example code demonstrates to us how can we use the AssociatedControlID property of label server control in an ASP.NET application.
LabelAssociatedControlID.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use associated control id (AssociatedControlID) in Label</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">Label Example: AssociatedControlID</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             ForeColor="CadetBlue"
             Text="<u>U</u>ser Name"
             ToolTip="Color label"
             AccessKey="U"
             AssociatedControlID="TextBox1"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1" 
             runat="server"
             BackColor="SeaGreen"
             ForeColor="AliceBlue"
             >
        </asp:TextBox>
    </div>
    </form>
</body>
</html>

RadioButton OnCheckedChanged event in asp.net

CheckedChanged event in RadioButton
RadioButton is an asp.net web server control. radio buttons are grouped logically when they share the same value for the GroupName property. Users can select one radio button at a time within a radio button group. GroupName property specifies a grouping of radio buttons to create a mutually exclusive set of controls.

RadioButton OnCheckedChanged method raises the CheckedChanged event of RadioButton control. This method allows us to write an event handler for the RadioButton CheckedChanged event.

RadioButton CheckedChanged event occurs when the Checked property value changes between posts to the server. This event only works when we set the RadioButton AutoPostBack property value to true. By using this event we can determine the checked status of RadioButton immediately after the user change the selection of RadioButton.

RadioButton Checked property gets or sets a value that indicates whether the RadioButton control is checked. The following ASP.NET c# example code demonstrates to us how can we use the CheckedChanged event in RadioButton server control.

In this example code, we create two RadioButton server controls and use the same name for the GroupName property. We write only an event handler for both RadioButtons CheckedChanged events. When the user changes the selection of a RadioButton in this RadioButton group then the CheckedChaged event raises and we can determine programmatically both RadioButton's current checked status.
RadioButtonOnCheckedChanged.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void RadioButton_CheckedChanged(object sender, System.EventArgs e)
    {
        if (RadioButton1.Checked == true)
        {
            Label1.Text = "You choose: " + RadioButton1.Text;
        }
        else
        {
            Label1.Text = "You choose: " + RadioButton2.Text;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use OnCheckedChanged event in RadioButton</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">RadioButton Example: OnCheckedChanged</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="OliveDrab"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="Crimson"
             Text="Favorite Control?"
             >
        </asp:Label>
        <br />
        <asp:RadioButton 
             ID="RadioButton1" 
             runat="server"
             Text="ValidationSummary"
             GroupName="Controls"
             OnCheckedChanged="RadioButton_CheckedChanged"
             AutoPostBack="true"
             />
        <asp:RadioButton 
             ID="RadioButton2" 
             runat="server"
             Text="CompareValidator"
             GroupName="Controls"
             OnCheckedChanged="RadioButton_CheckedChanged"
             AutoPostBack="true"
             />
    </div>
    </form>
</body>
</html>

How to use ListBox SelectedIndexChanged event in asp.net c#

ListBox SelectedIndexChanged Event
ListBox is an asp.net list web server control that contains a list of selectable items. More than one item is visible in ListBox control. ListBox SelectionMode property determines whether multiple items in the ListBox are selectable at a time.

ListBox SelectedIndexChanged event occurs when the SelectedIndex property or the SelectedIndices collection has changed. ListBox SelectedIndex property gets or sets the zero-based index of the currently selected item. And SelectedIndices property gets a collection that contains the zero-based indexes of all currently selected items in ListBox.

For multiple selections, the ListBox SelectedIndices property returns a collection containing the indexes of all selected items. ListBox SelectedIndexChanged event works when we set the ListBox AutoPostBack property value to True and write an event handler for the OnSelectedIndexChanged property.

when a user changes the selection of an item in a single selection mode ListBox control then the SelectedIndexChanged event occurs and the page post to the web server automatically. This event also occurs when the user adds or removes an item from multiple selected items in a multi-selection mode ListBox control.

The following c# example source code demonstrates to us how can we use ListBox SelectedIndexChanged event in asp.net.
ListBoxOnSelectedIndexChanged.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Label1.Text = "Your Favorite Color: " + ListBox1.SelectedItem.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use SelectedIndexChanged event in ListBox</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Maroon">ListBox: OnSelectedIndexChanged</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="SeaGreen"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="DarkCyan"
             Text="Color List"
             >
        </asp:Label>
        <br />
        <asp:ListBox 
             ID="ListBox1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
             BackColor="DarkCyan"
             ForeColor="AliceBlue"
             >
             <asp:ListItem>LawnGreen</asp:ListItem>
             <asp:ListItem>LightSalmon</asp:ListItem>
             <asp:ListItem>MediumBlue</asp:ListItem>
             <asp:ListItem>MediumOrchid</asp:ListItem>
             <asp:ListItem>Lavender</asp:ListItem>
        </asp:ListBox>
    </div>
    </form>
</body>
</html>

RadioButtonList SelectedIndexChanged event in asp.net c#

SelectedIndexChanged event in RadioButtonList
RadioButtonList is an ASP.NET list web server control that provides a single selection radio button group. RadioButtonList can be populated statically or dynamically from a data source object. RadioButtonList contains an item collection that holds ListItem objects. Each ListItem object represents an item (radio button) in RadioButtonList control.

RadioButtonList OnSelectedIndexChanged method raises the SelectedIndexChanged event. This method allows us to provide a custom handler for the SelectedIndexChanged event.

RadioButtonList SelectedIndexChanged event occurs when the item selection changes between posts to the web server. This event works only when we set the RadioButtonList control's AutoPostBack property value to True. AutoPostBack property gets or sets a value indicating whether a postback to the server automatically occurs when the user changes the list selection.

So when the user changes the RadioButtonList item selection then the SelectedIndexChanged event occurs and the page automatically postback to the server. After the postback, we can display the user selection result immediately on the web page.

The following ASP.NET C# example code demonstrates to us how can we use the SelectedIndexChanged event in RadioButtonList web server control.
RadioButtonListOnSelectedIndexChanged.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Label1.Text = "Your favorite: " + RadioButtonList1.SelectedItem.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use OnSelectedIndexChanged event in RadioButtonList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Maroon">RadioButtonList: OnSelectedIndexChanged</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="Teal"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             Text="Color List"
             >
        </asp:Label>
        <asp:RadioButtonList 
             ID="RadioButtonList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
             BackColor="DodgerBlue"
             ForeColor="AliceBlue"
             >
             <asp:ListItem>Cyan</asp:ListItem>
             <asp:ListItem>DarkBlue</asp:ListItem>
             <asp:ListItem>DarkGreen</asp:ListItem>
             <asp:ListItem>DarkSalmon</asp:ListItem>
             <asp:ListItem>Crimson</asp:ListItem>
        </asp:RadioButtonList>
    </div>
    </form>
</body>
</html>

How to use RadioButtonList AutoPostBack in asp.net c#

AutoPostBack feature in RadioButtonList
The following ASP.NET C# example code demonstrates to us how can we use the RadioButtonList AutoPostBack property/feature. RadioButtonList is an asp.net list web server control that renders a radio group on the web page. RadioButtonList provides a single selection/check radio group. Users can select an item from RadioButtonList at a time.

We can get the user selection from a RadioButtonList after page submission to the web server. RadioButtonList control has a property named AutoPostBack which allows us to automatically submit the page to web server each time the RadioButtonList item selection is changed. AutoPostBack property accepts a Boolean value.

If we set the AutoPostBack property value to true then each time we change the RadioButtonList item selection, it posts the web page to the server. If we set the AutoPostBack property value to false then it does not post the page to the server when we change the RadioButtonList item selection.

If we set the RadioButtonList control's AutoPostback property value to true and write an event handler for the SelectedIndexChanged event then we can get the selected item's text and value each time users change the item selection of RadioButtonList.
RadioButtonListAutoPostBack.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void RadioButtonList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use AutoPostBack feature in RadioButtonList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">RadioButtonList: AutoPostBack</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="SeaGreen"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="DarkCyan"
             Text="asp.net controls"
             >
        </asp:Label>
        <asp:RadioButtonList 
             ID="RadioButtonList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
             BackColor="DarkCyan"
             ForeColor="AliceBlue"
             >
             <asp:ListItem>HyperLink</asp:ListItem>
             <asp:ListItem>LayoutEditorPart</asp:ListItem>
             <asp:ListItem>BehaviorEditorPart</asp:ListItem>
             <asp:ListItem>Localize</asp:ListItem>
             <asp:ListItem>ImageMap</asp:ListItem>
        </asp:RadioButtonList>
    </div>
    </form>
</body>
</html>

asp.net - Add an item to a RadioButtonList programmatically

Add list item to RadioButtonList programmatically
RadioButtonList is an ASP.NET list web server control that allows us to render a single selection radio button group in the web browser. RadioButtonList control contains an item collection that holds all ListItem objects. We can populate a RadioButtonList control statically by declarative syntax. We also can populate a RadioButtonList control dynamically by data binding with a data source object.

RadioButtonList server control has built-in properties and methods to customize it. We can change the default look and feel of a RadioButtonList control. Even we can programmatically add or remove items from its items collection at run time.

Each ListItem object has three possible properties those are Text, Value, and Selected. We can create a ListItem object programmatically. We also can add this ListItem object to RadioButtonList control's Items collection programmatically. Items collection's Add(ListItem) method allows us to programmatically add a ListItem object to its collection.

Add method requires an argument that accepts a ListItem object. After adding a ListItem object to the items collection the RadioButtonList control displays this item in its radio button list.

The following ASP.NET C# example code demonstrates to us how can we add item in RadioButtonList server control programmatically at run time.
RadioButtonListAddItem.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ListItem li = new ListItem();
        li.Text = TextBox1.Text.ToString();
        RadioButtonList1.Items.Add(li);
        Label1.Text = "ListItem added in RadioButtonList: " + li.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to add list item in RadioButtonList programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">RadioButtonList example: Add List Item</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             Text="Color List"
             Font-Bold="true"
             ForeColor="Crimson"
             >
        </asp:Label>
        <br />
        <asp:RadioButtonList 
             ID="RadioButtonList1"
             runat="server"
             BackColor="Crimson"
             ForeColor="FloralWhite"
             RepeatColumns="2"
             >
             <asp:ListItem>SpringGreen</asp:ListItem>
             <asp:ListItem>Turquoise</asp:ListItem>
             <asp:ListItem>Violet</asp:ListItem>
             <asp:ListItem>SteelBlue</asp:ListItem>
             <asp:ListItem>Snow</asp:ListItem>
        </asp:RadioButtonList>
        <br /><br />
        <asp:Label 
             ID="Label3" 
             runat="server"
             ForeColor="Crimson"
             Text="Item Text"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="Crimson"
             ForeColor="Snow"
             >
        </asp:TextBox>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="Add List Item"
             Font-Bold="true"
             ForeColor="Crimson"
             OnClick="Button1_Click"
             />
    </div>
    </form>
</body>
</html>

How to add an item to BulletedList programmatically

Add an item to BulletedList programmatically
BulletedList is an ASP.NET list web server control. ASP.NET developers use BulletedList server control to create a list of items that are formatted with bullets. The BulletedList Items property gets the collection of items in the BulletedList control. Items collection contains all ListItem objects. A ListItem object represents a single item in BulletedList control.

ListItem object has three properties that are Text, Value, and Selected. Text property text is displayed in BulletedList control and Value property text is associated with ListItem and is hidden in the browser. The Selected property indicates whether ListItem is selected or not.

We can add ListItem objects of BulletedList server control at design time. We also can populate BulletedList by data binding with data source control. Even we can add items to BulletedList control programmatically at run time.

To add an item programmatically in BulletedList control, first, we need to create a ListItem object. Next, we need to add the ListItem object in the Items collection of BulletedList control. Now BulletedList will display the newly added item.

The following c# example code demonstrates to us how can we add an item in BulletedList server control programmatically (dynamically) at run time in ASP.NET.
BulletedListAddItem.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ListItem li = new ListItem();
        li.Text = TextBox1.Text.ToString();
        BulletedList1.Items.Add(li);
        Label1.Text = "ListItem added in BulletedList: " + li.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to add list item in BulletedList programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">BulletedList example: Add List Item</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="SeaGreen"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             Text="Color List"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             >
        </asp:Label>
        <br />
        <asp:BulletedList 
             ID="BulletedList1"
             runat="server"
             BackColor="DodgerBlue"
             ForeColor="Snow"
             Width="250"
             >
             <asp:ListItem>Magenta</asp:ListItem>
             <asp:ListItem>MediumBlue</asp:ListItem>
             <asp:ListItem>Orchid</asp:ListItem>
             <asp:ListItem>PaleGoldenRod</asp:ListItem>
             <asp:ListItem>Maroon</asp:ListItem>
        </asp:BulletedList>
        <br />
        <asp:Label 
             ID="Label3" 
             runat="server"
             ForeColor="DodgerBlue"
             Text="Item Text"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="DodgerBlue"
             ForeColor="Snow"
             >
        </asp:TextBox>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="Add List Item"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             OnClick="Button1_Click"
             />
    </div>
    </form>
</body>
</html>

CheckBoxList SelectedIndexChanged event in asp.net c#

CheckBoxList SelectedIndexChanged Event
Asp.net CheckBoxList web server control provides a multi-selection checkbox group. this is a list server control. list server control contains an Items collection that holds all ListItem Objects. ListItem objects have three useful properties they are Text, Value, and Selected.

CheckBoxList control's OnSelectedIndexChanged property raises the SelectedIndexChanged event. this property allows the developers to write a custom handler for the SelectedIndexChanged event.

The SelectedIndexChanged event is raised when the selection from the CheckBoxList control changes between posts to the server. so when a user changes a selection from CheckBoxList control then the SelectedIndexChanged event is raised and the page automatically posts to the web server. for that happening developers need to set the CheckBoxList AutoPostBack property value to True. when someone changes the selection from CheckBoxList then the page can immediately show the result using the SelectedIndexChanged event.

The following c# example source code demonstrates to us how can we use the SelectedIndexChanged event in asp.net CheckBoxList sever control.
CheckBoxListOnSelectedIndexChanged.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void CheckBoxList1_SelectedIndexChnaged(object sender, System.EventArgs e)
    {
        Label1.Text = "You Choose Color:<br /><i>";
        foreach (ListItem li in CheckBoxList1.Items)
        {
            if (li.Selected == true)
            {
                Label1.Text += li.Text + "<br />";
            }
        }
        Label1.Text += "</i>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use SelectedIndexChanged event in CheckBoxList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">CheckBoxList: OnSelectedIndexChanged</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="Crimson"
             Font-Size="Large"
             >
        </asp:Label>
        <br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="DarkBlue"
             Text="Color List"
             >
        </asp:Label>
        <asp:CheckBoxList 
             ID="CheckBoxList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChnaged"
             BackColor="DodgerBlue"
             ForeColor="FloralWhite"
             >
             <asp:ListItem>AntiqueWhite</asp:ListItem>
             <asp:ListItem>Ivory</asp:ListItem>
             <asp:ListItem>DarkViolet</asp:ListItem>
             <asp:ListItem>Lavender</asp:ListItem>
             <asp:ListItem>DeepPink</asp:ListItem>
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

How to use AutoPostBack in asp.net c# CheckBoxList

AutoPostBack feature in CheckBoxList
CheckBoxList is an ASP.NET web server control. This server control creates a multi-selection CheckBox group. CheckBoxList can be dynamically populated by binding the data source.

CheckBoxList AutoPostBack property gets or sets a value indicating whether a postback to the server automatically occurs when the user changes the CheckBoxList selection. This property value type is a Boolean.

If we set the property value to true then a postback automatically occurs when the user changes the CheckBoxList selection. And if we set this property value to false then automatic postback to the server will be disabled. The default value of this property is false.

CheckBoxList SelectedIndexChanged event occurs when the selection of CheckBoxList changes between posts to the server. to work this event properly we need to set the CheckBoxList AutoPostBack property value to true.

The following ASP.NET C# example code demonstrates to us how can we use the AutoPostBack property of CheckBoxList in an ASP.NET application.
CheckBoxListAutoPostBack.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void CheckBoxList1_SelectedIndexChnaged(object sender, System.EventArgs e)
    {
        Label1.Text = "You Selected:<br /><i>";
        foreach (ListItem li in CheckBoxList1.Items)
        {
            if (li.Selected == true)
            {
                Label1.Text += li.Text + "<br />";
            }
        }
        Label1.Text += "</i>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use AutoPostBack feature in CheckBoxList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Maroon">CheckBoxList: AutoPostBack</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="SeaGreen"
             Font-Size="Large"
             >
        </asp:Label>
        <br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="DarkBlue"
             Text="asp.net controls"
             >
        </asp:Label>
        <asp:CheckBoxList 
             ID="CheckBoxList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChnaged"
             >
             <asp:ListItem>Image</asp:ListItem>
             <asp:ListItem>TreeView</asp:ListItem>
             <asp:ListItem>Literal</asp:ListItem>
             <asp:ListItem>ValidationSummary</asp:ListItem>
             <asp:ListItem>MultiView</asp:ListItem>
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

asp.net - How to find an item by value from a DropDownList

DropDownList FindByValue(String) Method
DropDownList server control creates a single selection drop-down-list control. Asp.net developers can place ListItem objects between opening and closing tags of DropDownList control to specify list items. Each ListItem object represents a single item in DropDownList. Developers also can populate a DropDownList with items by using various data source controls such as SqlDataSource, LinqDataSource, ObjectDataSource, etc.

ListItem represents a data item in DropDownList control. ListItem Text property gets or sets the text displayed in DropDownList and the Value property gets or sets the value associated with the ListItem. Value is hidden in the browser.

We can find ListItem from a DropDownList Items collection programmatically by the specific ListItem value. DropDownList Items property gets the collection of items in DropDownList. The .net ListItemCollection class’s FindByValue() method searches a ListItem collection for a ListItem with a Value property that contains the specified value.

Following the asp.net c# example code help you to better understand how can you find a list item from DropDownList using item value.
DropDownListItemFindByValue.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    { 
       string searchString = TextBox1.Text.ToString();

       if (DropDownList1.Items.FindByValue(searchString) != null)
       {
           Label1.Text = "Item Found<br />Value: " + searchString;

           Label1.Text += "<br />Item Text: " + 
               DropDownList1.Items.FindByValue(searchString).Text;
       }
       else
       {
           Label1.Text ="Item not Found, Value: " + searchString;
       }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to find item by value from DropDownList</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            Find item by value from DropDownList
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label1"
            runat="server"
            Font-Bold="true"
            Font-Names="Comic Sans MS"
            ForeColor="Crimson"
            Font-Italic="true"
            Font-Size="X-Large"
            />
        <br /><br />
        <asp:Label 
            ID="Label2" 
            runat="server" 
            Text="List of asp.net controls"
            Font-Bold="true"
            ForeColor="Navy"
            Font-Size="X-Large"
            Font-Names="Courier New"
            Font-Underline="true"
            >
        </asp:Label>
        <br /><br />
        <asp:DropDownList 
            ID="DropDownList1"
            runat="server"
            BackColor="FloralWhite"
            ForeColor="DeepPink"
            Font-Names="Comic Sans MS"
            Font-Size="X-Large"
            Width="350"
            >
            <asp:ListItem Value="1">PasswordRecovery</asp:ListItem>
            <asp:ListItem Value="2">Menu</asp:ListItem>
            <asp:ListItem Value="3">SiteMapPath</asp:ListItem>
            <asp:ListItem Value="4">Repeater</asp:ListItem>
            <asp:ListItem Value="5">SqlDataSource</asp:ListItem>
        </asp:DropDownList>
        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br />
        <asp:Label 
            ID="Label3" 

            runat="server"
            ForeColor="Navy"
            Text="Item Value"
            Font-Bold="true"
            >
        </asp:Label>
        <asp:TextBox 
            ID="TextBox1"
            runat="server"
            Font-Bold="true"
            Font-Size="Large"
            Height="30"
            BackColor="Gold"
            Font-Names="Courier New"
            >
        </asp:TextBox>
        <br /><br />
        <asp:Button 
            ID="Button1" 
            runat="server"
            Text="Find In DropDownList"
            OnClick="Button1_Click"
            Font-Bold="true"
            Font-Size="Large"
            ForeColor="Navy"
            Font-Names="Monaco"
            Height="55"
            Width="350"
            />
    </div>
    </form>
</body>
</html>

asp.net - How to find an item by text in a DropDownList

DropDownList.Items.FindByText(String) Method
DropDownList represents a control that allows the user to select a single item from a drop-down list. The .NET developers can populate a DropDownList control by items using data bind with a data source control. They also can specify DropDownList items by placing ListItem objects between opening and closing DropDownList tags using declarative syntax.

ListItem object has a Text property that gets or sets the text displayed in DropDownList. And have a Value property that is associated with the ListItem. Value property value is hidden in the web browser.

We can find a DropDownList item by its Text property programmatically at run time. The .NET ListItemCollection class’s FindByText() method searches the item collection for a ListItem with a Text property that equals the specified text. This method is case-sensitive and culture-insensitive. The null is returned if this method does not find an item.

The following ASP.NET C# example source code demonstrates to us how can we find a list item from DropDownList using specified item text.
DropDownListItemFindBytext.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    { 
       string searchString = TextBox1.Text.ToString();
       if (DropDownList1.Items.FindByText(searchString) != null)
       {
           Label1.Text = "Item Found: " + searchString;
       }
       else
       {
           Label1.Text ="Item not Found: " + searchString;
       }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to find item by text in DropDownList, FindByText()</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">DropDownList example: Find By Text</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="SaddleBrown"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             Text="asp.net controls"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             >
        </asp:Label>
        <br />
        <asp:DropDownList 
             ID="DropDownList1"
             runat="server"
             BackColor="Crimson"
             ForeColor="FloralWhite"
             >
             <asp:ListItem>Repeater</asp:ListItem>
             <asp:ListItem>LoginName</asp:ListItem>
             <asp:ListItem>DataList</asp:ListItem>
             <asp:ListItem>LoginView</asp:ListItem>
             <asp:ListItem>LinqDataSource</asp:ListItem>
        </asp:DropDownList>
        <br /><br />
        <asp:Label 
             ID="Label3" 
             runat="server"
             ForeColor="SaddleBrown"
             Text="Item Text"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="SaddleBrown"
             ForeColor="Snow"
             >
        </asp:TextBox>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="Find In DropDownList"
             Font-Bold="true"
             ForeColor="SeaGreen"
             OnClick="Button1_Click"
             />
    </div>
    </form>
</body>
</html>

How to use DropDownList AutoPostBack in asp.net c#

DropDownList AutoPostBack Feature
DropDownList control allows users to select an item from a single selection drop-down list. We can specify DropDownList items by placing ListItem elements between the opening and closing tags of the DropDownList control.

The .NET developers can also populate DropDownList from a data source object such as SqlDataSource, ObjectDataSource, LinqDataSource, ArrayList, Array, etc. The DropDownList DataBind method binds the data source to the DropDownList control.

Users can select an item from DropDownList and manually submit the form using submit button to send their selection to the server. This way we can get user selection by clicking a submit button. But ASP.NET DropDownList is a more user-friendly server control. It has a property name AutoPostBack. AutoPostBack property works with the SelectedIndexChanged event.

AutoPostBack property gets or sets a value that indicates whether a postback to the server automatically occurs when the user changes the list selection. The OnSelectedIndexChanged method raises the SelectedIndexChanged event that allows developers to provide a custom handler for the event.

The SelectedIndexChanged event is raised when the user changes the DropDownList selection. So when if the user changes the DropDownList item selection then the page automatically posts to the web server and the developer can display user selection details on the web page after postback occurs.

The following C# example source code describes more how can you use the DropDownList AutoPostBack feature in ASP.NET to provide a better user experience.
DropDownListAutoPostBack.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Label1.Text = "You Selected: " + DropDownList1.SelectedItem.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DropDownList AutoPostBack feature</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">DropDownList: AutoPostBack</h2>
        <asp:Label 
             ID="Label1"
             runat="server"
             Font-Bold="true"
             ForeColor="Purple"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2"
             runat="server"
             Font-Bold="true"
             ForeColor="OrangeRed"
             Text="asp.net controls"
             >
        </asp:Label>
        <asp:DropDownList 
             ID="DropDownList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
             >
             <asp:ListItem>HyperLink</asp:ListItem>
             <asp:ListItem>PasswordRecovery</asp:ListItem>
             <asp:ListItem>PlaceHolder</asp:ListItem>
             <asp:ListItem>LoginName</asp:ListItem>
             <asp:ListItem>Label</asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

How to find ListBox item by text in asp.net c#

Find ListBox Item By Text
ListBox is an ASP.NET list web server control. Developers can use the ListBox control to create a single or multi-item selection list control. We can set single selection or multi-selection mode using the ListBox SelectionMode property. ListBox Items property contains all ListItem objects.

ListBox can populate with items from a data source control. So a ListBox can exists many items. Each ListItem object has a Text and a Value property. Text property holds the text to display in ListBox and Value property text is associated with the ListItem object and is hidden in the web browser.

The .NET C# developers can find/search a ListItem object in ListBox using the ListItem Text property value. To find an item using its Text we need to use the Items FindByText(String) method. Items FindByText() method finds an item from ListBox using its Text property string.

The following C# example source code demonstrates to us how can we find a ListBox item by text in ASP.NET.
ListBoxFindItemByText.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    { 
       string searchString = TextBox1.Text.ToString();
       if (ListBox1.Items.FindByText(searchString) != null)
       {
           Label1.Text = "Item Found: " + searchString;
           ListBox1.Items.FindByText(searchString).Selected = true;
       }
       else
       {
           Label1.Text ="Item not Found: " + searchString;
       }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to find item by text in ListBox, FindByText()</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">ListBox example: Find By Text</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Font-Bold="true"
             ForeColor="Red"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             Text="asp.net controls"
             Font-Bold="true"
             ForeColor="DarkGreen"
             >
        </asp:Label>
        <br />
        <asp:ListBox 
             ID="ListBox1"
             runat="server"
             BackColor="DarkGreen"
             ForeColor="FloralWhite"
             >
             <asp:ListItem>ListBox</asp:ListItem>
             <asp:ListItem>XmlDataSource</asp:ListItem>
             <asp:ListItem>SqlDataSource</asp:ListItem>
             <asp:ListItem>BulletedList</asp:ListItem>
             <asp:ListItem>RadioButton</asp:ListItem>
        </asp:ListBox>
        <br /><br />
        <asp:Label 
             ID="Label3" 
             runat="server"
             ForeColor="HotPink"
             Text="Item Text"
             >
        </asp:Label>
        <asp:TextBox 
             ID="TextBox1"
             runat="server"
             BackColor="HotPink"
             ForeColor="Snow"
             >
        </asp:TextBox>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="Find"
             Font-Bold="true"
             ForeColor="DarkGreen"
             OnClick="Button1_Click"
             />
    </div>
    </form>
</body>
</html>

How to data bind ListBox programmatically in asp.net c#

Data bind ListBox programmatically
ListBox is an ASP.NET list web server control. ListBox control's items collection contains ListItem objects. We can populate a ListBox with items by declarative syntax. We can place the ListItem element between the opening and closing tags of the ListBox control to display it in the browser.

ListBox server control supports data binding. To bind the ListBox control to a data source control, developers need to first create a data source such as a DataSourceControl object. DataSourceControl serves as the base class for controls that represent data sources to data-bound controls. The DataSourceControl object contains the items to display in the ListBox.

Next developers can call the ListBox DataBind method to bind the data source to the ListBox. ListBox DataTextFiled and DataValueField properties specify which field in the data source to bind the Text and Value properties. After data binding, ListBox control will display data source data.

The following C# example code demonstrates to us how can we data-bind ListBox control with data source programmatically at run time. This code creates a String array data source and binds data with ListBox control. ListBox displays array elements as list items.
ListBoxDataBind.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        // Initialize a new array
        string[] controls = {
            "Login",
            "ValidationSummary",
            "RegularExpressionValidator",
            "DataList", "GridView"
        };

        // Specify the ListBox data source
        ListBox1.DataSource = controls;

        // Finally, data bind the ListBox
        ListBox1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to data bind ListBox programmatically</title>
</head>
<body style="padding:25px">
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">      
            Data bind ListBox programmatically
        </h2>      
        <hr width="450" align="left" color="Gainsboro" />
        <asp:Label
            ID="Label1"
            runat="server"
            Text="ASP.NET Controls"
            Font-Bold="true"
            ForeColor="Navy"
            Font-Size="Large"
            >
        </asp:Label>
        <br />
        <asp:ListBox
            ID="ListBox1"
            runat="server"
            AutoPostBack="false"
            BackColor="Tomato"
            ForeColor="FloralWhite"
            Font-Names="Comic Sans MS"
            Font-Size="X-Large"
            />
        <br /><br />
        <asp:Button
            ID="Button1"
            runat="server"
            Text="DataBind ListBox"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            Height="45"
            Width="150"
            OnClick="Button1_Click"
            />
    </div>
    </form>
</body>
</html>

ColdFusion: How to invoke a method of a component

Introduction

In Adobe ColdFusion, one of the most powerful features is the ability to create reusable code components known as ColdFusion Components (CFCs). These components allow developers to encapsulate functionality into manageable and modular code blocks. One common task in ColdFusion development is invoking methods from these components in order to execute specific functionality or retrieve data. ColdFusion provides the <cfinvoke> tag to facilitate this process, allowing developers to easily call methods from a component (CFC). Additionally, the <cfinvokeargument> tag is used to pass arguments to the method being invoked.

In this tutorial, we'll explore how to invoke a method from a CFC using the <cfinvoke> and <cfinvokeargument> tags, demonstrated by a simple example that retrieves table data from a database.

Component Overview

The tutorial consists of two files: cfinvokeargument.cfm and TableData.cfc. The first file is a ColdFusion page that demonstrates how to invoke a method of a component, while the second file is a ColdFusion Component (CFC) that contains the method to be invoked.

In TableData.cfc, there is a function called GetTableData that accepts two arguments: Table and Columns. This method constructs a SQL query using the provided arguments and returns the result as a ColdFusion query object. This component allows for flexible data retrieval from any table by dynamically selecting the table and columns based on the arguments passed in.

Using <cfinvoke> to Call the Component

The ColdFusion page (cfinvokeargument.cfm) is where the invocation of the component method happens. The <cfinvoke> tag is used to call the GetTableData method from the TableData component. The component attribute specifies the CFC to be invoked (TableData.cfc), while the method attribute specifies the method to be called (GetTableData). The returnvariable attribute stores the result of the method, which is returned as a ColdFusion query object.

The use of <cfinvoke> allows for a clean and modular way to access the functionality of a CFC without the need to hard-code method calls, making it ideal for situations where the component may need to be called multiple times or reused across different pages.

Passing Arguments with <cfinvokeargument>

To pass the necessary data to the GetTableData method, the <cfinvokeargument> tag is used inside the <cfinvoke> block. In this example, two arguments are passed: Table, which specifies the name of the database table (in this case, "Employees"), and Columns, which lists the columns to be retrieved (e.g., "FirstName, LastName, Email"). These arguments correspond to the parameters expected by the GetTableData method in TableData.cfc.

Each argument is defined with a name attribute (which must match the argument name in the method definition) and a value attribute (the actual value to be passed to the method). This approach makes it easy to dynamically pass values to component methods.

Displaying the Results

Once the method has been invoked and the data has been returned, the <cfdump> tag is used to display the results of the query on the page. The <cfdump> tag provides a quick and easy way to output complex variables such as queries, allowing developers to inspect the returned data and ensure the component method is functioning as expected.

In this example, the query results will include the first name, last name, and email of employees from the Employees table, based on the arguments passed via <cfinvokeargument>.

Summary

In this tutorial, we've explored how to use the <cfinvoke> and <cfinvokeargument> tags in ColdFusion to invoke a method from a ColdFusion component (CFC). By encapsulating data retrieval logic in a component, and using ColdFusion's native tags to pass arguments and invoke methods, you can create highly modular and reusable code. This technique not only streamlines development but also enhances the flexibility and maintainability of your applications, allowing you to easily adapt components for different use cases.

The example demonstrated here is a basic use case, but these tags are extremely powerful for more complex operations, including API integrations, database interactions, and other dynamic web functionalities.


cfinvokeargument.cfm

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cfinvoke and cfinvokeargument tag example: how to invoke a method of a component</title>
</head>

<body>
<h2 style="color:DodgerBlue">ColdFusion cfinvoke and cfinvokeargument example</h2>

<cfinvoke 
 component="TableData" 
    method="GetTableData" 
    returnvariable="qTableData"
    >
 <cfinvokeargument name="Table" value="Employees">
    <cfinvokeargument name="Columns" value="FirstName,LastName,Email">
</cfinvoke>    
<cfdump var="#qTableData#">

</body>
</html>



TableData.cfc

<cfcomponent hint="Table Data Viewer">
 <cffunction name="GetTableData" access="remote" returntype="query">
        <cfargument name="Table" type="string" required="yes">
  <cfargument name="Columns" type="string" required="yes">
  <cfquery name="qTable" datasource="cfdocexamples">
         SELECT #arguments.Columns# FROM #arguments.Table#
        </cfquery>
  <cfreturn qTable>
 </cffunction>
</cfcomponent>





More ColdFusion examples

How to invoke a method of a component in ColdFusion

Introduction

This tutorial demonstrates how to invoke a method of a ColdFusion component (CFC) using the <cfinvoke> tag. ColdFusion components are reusable modules that encapsulate data and functionality, and they are an essential part of ColdFusion's object-oriented programming approach. The example provided shows how to interact with a component to retrieve data from a database table dynamically. By the end of this tutorial, you will understand how to define a CFC, create methods within the component, and call those methods using <cfinvoke> in ColdFusion.

In this example, we have two files: cfcomponent.cfm, which acts as the main interface for invoking the component, and DataViewer.cfc, which contains the logic for retrieving data from a database. Let’s break down the code step by step to understand the roles of these files and how they interact with each other.

Defining the Component in ColdFusion

The core of this example is the DataViewer.cfc file, which defines the component. In ColdFusion, components are declared using the <cfcomponent> tag. The component is a self-contained module that can contain multiple functions (methods) to perform specific tasks. In this case, the component is responsible for retrieving table data from a database.

The component is given a simple descriptive hint, "Table Data Viewer," which helps explain its purpose. Inside the component, there is one function, GetTableData, which performs the task of querying a database and returning the data. This encapsulation of functionality makes it easy to reuse and maintain the code.

Method Definition with cffunction

Inside the DataViewer.cfc component, the GetTableData method is defined using the <cffunction> tag. The function is set to be accessible remotely, meaning it can be called from other ColdFusion files or even from external sources if necessary. The return type of this function is specified as a query, which indicates that the function will return a set of database records.

The function takes two arguments: DSname (the name of the data source) and Table (the name of the table from which data is to be retrieved). Both arguments are required, and their data types are set as strings. This ensures that the function will only execute if the correct parameters are provided.

Querying the Database

Within the GetTableData function, the <cfquery> tag is used to perform the database query. The datasource attribute of the <cfquery> tag is dynamically set using the DSname argument passed to the function, allowing the function to be flexible and connect to different data sources as needed.

The SQL query itself is straightforward: it selects all columns from the table specified by the Table argument. By using dynamic arguments in the query, this function can be reused to fetch data from various tables without modifying the underlying code. After executing the query, the function returns the result as a ColdFusion query object.

Invoking the Component with cfinvoke

In the cfcomponent.cfm file, the ColdFusion <cfinvoke> tag is used to call the GetTableData method from the DataViewer component. The <cfinvoke> tag allows developers to call methods from ColdFusion components without directly interacting with the CFC file.

The component attribute specifies the name of the component (DataViewer), and the method attribute defines the function to be invoked (GetTableData). The DSname and Table attributes provide the required arguments for the function, allowing it to retrieve data from the specified data source and table. The result of the function call is stored in a variable named qTableData using the returnvariable attribute.

Displaying the Results

After invoking the component and retrieving the data, the <cfdump> tag is used to display the result. The <cfdump> tag is a debugging tool in ColdFusion that outputs the contents of variables in a readable format, making it easy to view and inspect the query results. In this case, it will display the entire dataset returned from the Employees table.

Conclusion

This tutorial demonstrates how to invoke a method of a ColdFusion component using the <cfinvoke> tag. By encapsulating the database query logic within a CFC, you can create reusable components that simplify data access across your ColdFusion applications. The example also highlights the flexibility of ColdFusion components, allowing you to pass dynamic parameters and return structured data.

Using ColdFusion's component-based architecture can significantly improve code organization and reusability, making your applications easier to maintain and extend. Whether you are working with simple queries or complex business logic, ColdFusion components and the <cfinvoke> tag provide a powerful way to modularize and manage functionality in your projects.


cfcomponent.cfm

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cfcomponent and cfinvoke tag example: how to invoke a method of a component</title>
</head>

<body>
<h2 style="color:DodgerBlue">ColdFusion cfcomponent and cfinvoke example</h2>

<cfinvoke 
 component="DataViewer" 
    method="GetTableData" 
    DSname="cfdocexamples"
    Table="Employees" 
    returnvariable="qTableData"
    >
<cfdump var="#qTableData#">

</body>
</html>

DataViewer.cfc

<cfcomponent hint="Table Data Viewer">
 <cffunction name="GetTableData" access="remote" returntype="query">
  <cfargument name="DSname" type="string" required="yes">
        <cfargument name="Table" type="string" required="yes">
  <cfquery name="qTable" datasource="#arguments.DSname#">
         SELECT * FROM #arguments.Table#
        </cfquery>
  <cfreturn qTable>
 </cffunction>
</cfcomponent>





More ColdFusion examples