2

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?

1
  • 1
    This is just bad. You should leave front-end logic to front-end. Why not just add javascript code into your HTML that will listen on table-row clicks and then display the appropriate message? Commented May 6, 2013 at 21:02

6 Answers 6

3

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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));
        }
    }
}

1 Comment

thanks for the answer and all the work you went to, I appreciate it. While I've got a working solution, I want to incorporate your methods because I agree they're cleaner. Thanks again and I'll accept your answer once I've done the incorporation.
1

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: "

3 Comments

Thanks, but as pointed out in the OP, that's not the problem.
Strange, I am sure that if you leave the single quote it doesn't work because there are many questions here on this case. Could you try with the Unicode \u0027 escape character? See a similar problem in this question
thanks for the link & the suggestion. I tried using the unicode string, but I still get nothing when I click on the textbox. So then I tried a simple string in there, & voila, it worked. So, I added the row number to the simple string (just five random alpha characters), and that works as well. So I thought it must be something else in the original string, I eliminated the colon, spaces, etc as culprits. Now I'm using "You have selected row: " + selectedRow.ToString(); which is working. I'm still mystified because I don't see anything that's changed all that much.
0

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

1 Comment

Thanks, but as pointed out in the OP, that's not the problem.
0

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.

1 Comment

Thanks for the suggestion, but this isn't exactly what I need.
0

in javascript write a C# string in an alert

@:alert('@name');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.