delliottg
delliottg

Reputation: 4140

Insert C# string variable into Javascript alert in ASP.NET code behind

I'm using a Gridview with some text boxes and a drop down box in it. When the user clicks on a row (text box or DDL), I want to pop up a Javascript alert that tells them what the row number is. I can get an event to fire when a user clicks on one of the text boxes, but I can't tell them which row it is inside the alert because I can't seem to figure out how to put a C# variable into a Javascript alert.

Here's what I've tried:

public void gv_instruments_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       TextBox txtBox1 = (TextBox)e.Row.FindControl("txt_partNumbers");
       if (txtBox1 != null)
       {
           txtBox1.Attributes.Add("onclick", "javascript:alert('Message')"); //works

           Int32 selectedRow = e.Row.RowIndex;//get row index number
           string message = "You've selected row: " + selectedRow.ToString();
           message = "javascript:alert('" + message + "')";

           //txtBox1.Attributes.Add("onclick", message); //doesn't work 

           string title = "title";
           //ScriptManager.RegisterStartupScript(Page, Page.GetType(), 
                title, "alert('" + message + "');", true); //doesn't work

           //ScriptManager.RegisterClientScriptBlock(Page,Page.GetType(), 
                title, "alert('" + message + "');",true); //doesn't work
            }
        }
    }

I've found pages on the internet that use the "javascript:alert('" + message + "')"; construct, but it doesn't work (or at least I can't get it to work). I've been careful with the double quotes & single quotes and I can see what looks like a valid message in the debugger (EG: javascript:alert('You've selected row: 0'), I also thought the apostrophe in "you've" might have been the problem, so I removed that & replaced it with "you have", but that doesn't work either. The only construct that I can get to work is this:

txtBox1.Attributes.Add("onclick", "javascript:alert('Message')");

What am I missing?

Upvotes: 2

Views: 11240

Answers (6)

rog wool
rog wool

Reputation: 420

in javascript write a C# string in an alert

@:alert('@name');

Upvotes: 0

anandd360
anandd360

Reputation: 306

just try this

string noofrows = dt.Rows.Count.ToString();
string message = "alert('"+ noofrows +" rows found')";
ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(),"alert", message, true);
return;

Upvotes: 3

Win
Win

Reputation: 62290

If you move your javascript to front end, your code will be a lot cleaner.

Here is an example which displays an alert box if you click on a textbox.

enter image description here

<script type="text/javascript">
    function showMessage(id) {
        alert('You have selected row: ' + id);
    }
</script>        
<asp:GridView runat="server" ID="gv_instruments" 
    OnRowDataBound="gv_instruments_RowDataBound"
    AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField HeaderText="Id" DataField="Id" />
        <asp:BoundField HeaderText="FirstName" DataField="FirstName" />
        <asp:BoundField HeaderText="LastName" DataField="LastName" />
        <asp:TemplateField HeaderText="Click Me">
            <ItemTemplate>
                <asp:TextBox runat="server" ID="txt_partNumbers">
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var collection = new List<User>()
            {
                new User {Id = 1, FirstName = "John", LastName = "Doe"},
                new User {Id = 2, FirstName = "Marry", LastName = "Doe"},
                new User {Id = 3, FirstName = "David", LastName = "Newton"},
            };

        gv_instruments.DataSource = collection;
        gv_instruments.DataBind();
    }
}

public void gv_instruments_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var txtBox1 = (TextBox) e.Row.FindControl("txt_partNumbers");
        if (txtBox1 != null)
        {
            txtBox1.Attributes.Add("onclick", 
              string.Format("showMessage('{0}')", e.Row.RowIndex));
        }
    }
}

Upvotes: 2

OnoSendai
OnoSendai

Reputation: 3970

You may try populating all buttons with the ItemIndex property at render time, like this:

txtBox1.Attributes.Add(
    "onclick", 
    "javascript:alert('" + e.Item.ItemIndex.ToString() + "')"
    );

At line 8 in your example.

Upvotes: 0

Shai Aharoni
Shai Aharoni

Reputation: 1957

Your problem occurs beacuse of the apostrophe (') in "You've" . You should escape the apostrophe and use : "You\'ve selected row: "

Upvotes: 0

Steve
Steve

Reputation: 216313

Probably it doesn't work because the second message contains a single quote.

"You've selected row: "
    ^

Try to write

"You&apos;ve selected row: "

Upvotes: 1

Related Questions