I am using a asp.net listbox. I have two buttons one to add items to listbox and another to remove. I am using javascript function to remove items from the listbox. When I add to the listbox after removing. The removed items are also getting added.
<asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox>
<asp:LinkButton ID="sLbtnAdd" runat="server" ></asp:LinkButton>
Remove
function fncRemoveItems()
{
var i;
var strIDs="";
var items = document.getElementById("sLstbox");
alert(items.options.length);
for (i = items.options.length - 1; i >= 0; i--)
{
if (items.options[i].selected)
items.remove(i);
}
}
IN code
Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
Dim li As New ListItem
li.Value = "1"
li.Text = "test"
sLstbox.Items.Add(li)
End Sub
You should be using normal < select > boxes in this case.
asp:listboxes are meant to be manipulated at server side and you need to hack around that to make it work the way you want.
With normal select-boxes (either runat server or not) it should be pretty straight forward.
If you want to make your life a lot easier and give you the 'AJAX' effect, just put it all in an UpdatePanel and do it server side. If you want to use an asp:ListBox, manipulating it via javascript is going to a pain.
Here is a working example with the aspx code and the codebehind implementation for your scenario:
<asp:UpdatePanel ID="yourUpdatePanel" runat="server">
<ContentTemplate>
<asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox>
<asp:LinkButton ID="sLbtnAdd" runat="server" OnClick="sLbtnAdd_Click" ></asp:LinkButton>
<asp:LinkButton ID="sLbtnRemove" runat="server" OnClick="sLbtnRemove_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
In your codebehind:
Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
Dim li As New ListItem
li.Value = "1"
li.Text = "test"
sLstbox.Items.Add(li)
End Sub
Protected Sub sLbtnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
For i As Integer = sLstbox.Items.Count - 1 To 0 Step -1
If sLstbox.Items(i).Selected Then
sLstbox.Items.Remove(sLstbox.Items(i))
End If
Next
End Sub
Related
Good day,
I have a repeater that contain link button. The value and number of link button is generate base on data pull from database. The HTML code is something as follow:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
Here is some code that I try to do in my code behind,
for (int i = 0; i < table.Rows.Count; i++)
{
RepeaterItem itm = repCategories.Items[i];
GiftRow dr = tbl.GetRow(i);
Literal litLink2 = (Literal)itm.FindControl("litLink2");
litLink2.Text = dr.Name;
string myScript = string.Empty;
myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
}
By doing this, I will get alert hi when I load the page.What I want to do is, I only want it do alert hi when I click on the link button, instead of page load.
Use a LinkButton and leverage the ClientClick event instead:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
<asp:LinkButton ID="lbMyLinkButton" runat="server" />
</ItemTemplate>
</asp:Repeater>
I'd also recommend you use ItemDataBound events of repeaters where possible:
void repCategories_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((LinkButton)e.Item.FindControl("lbMyLinkButton")).OnClientClick = "alert('hi');";
}
}
NOTES:
I wouldn't ever recommend you render javascript server-side unless absolutely necessary. I've provided an answer to fit in with the context of your question, but I would advise you have a javascript function already on your page and 'wire it up' server-side (if not bind it on the client with pure javascript)
There is also an assumption here that you're binding data to the repeater (you should be anyway), which means you also have to wire up the ItemDataBound handler: repCategories.OnItemDataBound += repCategories_ItemDataBound
within a gridview, i have a template column, which has a linkButtton column within it.
when the linkButton column is clicked, it triggers the client side, which if TRUE should call the server side event.
but somehow, the server side event is been invoked in both cases - TRUE or FALSE.
please let me know, if i'm missing on something......
markup code goes as --
<asp:TemplateField HeaderText="Disable/Enable" ItemStyle-Width="10%" HeaderStyle-HorizontalAlign="Left"#
<ItemTemplate>
<asp:LinkButton runat="server" ID="ableDisableLaborCode" CommandName="linkButtonClick" CommandArgument='#%# Eval("coLaborCodeID") %#'##/asp:LinkButton#
</ItemTemplate>
</asp:TemplateField>
This is where the client side event is registered
Private Sub gridVwCoLaborCodes_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridVwCoLaborCodes.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim _lnk As LinkButton = DirectCast(e.Row.FindControl("ableDisableLaborCode"), LinkButton)
Dim _drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
_lnk.Text = If(CBoolBit(_drv(Fields.NAME_FIELD_IS_ENABLED_FLAG)), "Disable", "Enable")
_lnk.OnClientClick = String.Format("return confirm('Are you sure you want to deactivate this labor code ?');")
End If
End Sub
following is the code for the server side event --
Private Sub gridVwCoLaborCodes_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridVwCoLaborCodes.RowCommand
If e.CommandName = "linkButtonClick" Then
CoLaborCodeId = CIntNull(e.CommandArgument.ToString())
End If
End Sub
thanks to all viewed and helped.
Try to assign the javascript event in a different way:
Private Sub gridVwCoLaborCodes_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridVwCoLaborCodes.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim _lnk As LinkButton = DirectCast(e.Row.FindControl("ableDisableLaborCode"), LinkButton)
Dim _drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
_lnk.Attributes.Add("onclick", "return confirm('Are you sure you want to deactivate this labor code ?');")
lnk.Text = If(CBoolBit(_drv(Fields.NAME_FIELD_IS_ENABLED_FLAG)), "Disable", "Enable")
End If
End Sub
How do I go about getting the selected value from the DropDownList in asp.Net using selectedIndexChanged with an update Panel? I've tried but when I add the AutoPostBack to my DropDownList, it sends me to an error page saying it cannot find the resource.(doesn't even hit my "selected_IndexChanged") I have the hiddenField being assigned the selected value.
Here is my DropDownList:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="300px"
AutoPostBack="true" OnSelectedIndexChanged="ddlCaseFilesNew_SelectedIndexChanged" Visible="False">
<asp:ListItem>Item 1</asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlCaseFilesNew" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
When I click on a value inside the DropDownList it sends me to a "cannot find resource" page. I have no idea why. It doesn't even touch my "onSelectedIndexChanged"
<script runat="server">
protected void ddlCaseFilesNew_SelectedIndexChanged(object sender, EventArgs e)
{
hidNewCaseFile.Value = ddlCaseFilesNew.SelectedItem.Value;
}
</script>
In your SelectedIndex function, use
string sValue = ((DropDownList)sender).SelectedValue;
Since it's in an update panel, you likely won't have access to it via the designer (this.DdlId).
Based on your comment in the OP, this is likely what you need:
protected void ddlCaseFilesNew_SelectedIndexChanged(object sender, EventArgs e)
{
hidNewCaseFile.Value = ((DropDownList)sender).SelectedValue;
}
You also need to move your hidden field into the ContentTemplate.
Use:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var res = this.myDropDownList.SelectedValue;
}
Or:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = sender as DropDownList;
var res = ddl.SelectedValue;
}
Edit 1
You need to understand that the partial page rendering occurs for all controls inside an UpdatePanel, in your case, you are trying to set the Value property of hidNewCaseFile control which does not appear to be inside the UpdatePanel therefore, its value will never get updated
I tried
Protected Sub btn_add_question_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add_question.Click
frm_course.Visible = False
question_div.Visible = True
ScriptManager.RegisterClientScriptBlock(btn_add_question, Me.GetType(), "BlockName", "alert('hello world');", True)
End Sub
and
Protected Sub btn_add_question_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add_question.Click
frm_course.Visible = False
question_div.Visible = True
Page.ClientScript.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello')")
End Sub
But, alert message is not showing. Need Help !!
<asp:Button ID="btn_add_question" runat="server" Text="Next" CssClass="btn_submit" Width="101px" />
You need to add the <script> tags to the function call by passing True as the last parameter to RegisterStartupScript as so:
Page.ClientScript.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello');",True)
UPDATE:
Try this:
ScriptManager.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello');",True)
add an OnClientClick handler to the button or, better yet, attach the handler through javascript where it should be.
<asp:button id="myButton" runat="server" text="Postback" onclientclick="alert('hello world');" />
if all you are doing is changing some visibility of some elements, you shouldn't even be doing a post back at all. just use an input type="button" and show/hide through javascript.
<input type="button" value="Next" id="btn_add_question" />
document.getElementById('btn_add_question').onclick = function () {
document.getElementById('frm_course').style.visibility = 'hidden';
document.getElementById('question_div').style.visibility = 'visible';
alert('hello world');
};
I have a gridview displaying all employees. Upon selecting an employee, I'd like to open a new page or window that would display all of the information for that employee with the option to edit/delete/update. Once this transaction is complete, return to previous page with gridview of all employees. ((language I'm usings is VB))
----- code in gridview ---
<asp:TemplateField Visible="true" headertext="Select">
<ItemTemplate>
<asp:HiddenField ID="hdID01" runat="server" Value='<%# Eval ("PersonnelID") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
------ code behind ----
Protected Overridable Sub Grid_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' Click to highlight row
Dim lnkSelect As Control = e.Row.FindControl("lnkSelect")
If lnkSelect IsNot Nothing Then
Dim click As New StringBuilder()
click.AppendLine(GridView1.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty))
click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex))
e.Row.Attributes.Add("onclick", click.ToString())
End If
End If
End Sub
------ Javascript -----
<script type="text/javascript">
var selectedRowIndex = null;
function onGridViewRowSelected(rowIndex) {
selectedRowIndex = rowIndex;
}
function editItem() {
if (selectedRowIndex == null) return;
var cell = gridView.rows[parseInt(selectedRowIndex) + 1].cells[0];
var hidID = cell.childNodes[0];
window.open('mg_edit.aspx?id=' + hidID.value);
}
Nothing happens when selected. ??? I need help!
One of these links should give you a better direction about what you are trying to accomplish with a GridView:
http://www.codeproject.com/KB/webforms/GridViewConfirmDelete.aspx
http://weblogs.asp.net/scottgu/archive/2006/01/02/434362.aspx
Or, you may want to consider using a ListView control if you are using 3.5 or higher:
http://basgun.wordpress.com/2008/01/06/onclick-tooltip-listview/
Good luck!