Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem adding JavaScript OnClick to Datagrid Delete button 1

Status
Not open for further replies.

DLLHell

Programmer
May 9, 2003
69
US
I am having problems with trying to add a JavaScript Onclick function to a DataGrid's Delete function - the Delete otherwise works. I am new to C#/ASP.NET - any idea why this does not work?

Thanks in advance for any help or clues.

The Delete Button is a template column in the DataGrid:
<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton runat=&quot;server&quot;
Text=&quot;Delete&quot;
CommandName=&quot;Delete&quot;
CausesValidation=&quot;false&quot;>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>

public void DataGrid1_ItemDataBound (object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem )
{
Button b = (Button)e.Item.FindControl(&quot;Delete&quot;);
string n = (string)DataBinder.Eval (e.Item.DataItem, &quot;blahblah&quot;);
string js = &quot;return confirm('Are you sure you want to delete ' + n + '?');&quot;;
b.Attributes.Add(&quot;onclick &quot;, js);
}
}

The ItemDataBound event raises this error:

System.NullReferenceException: Object reference not set to an instance of an object.
b.Attributes.Add(&quot;onclick &quot;, js);
 
You are missing an id of your button so findcontrol probably does not find the button.
Since this button is on every row there will be several instancis of this button.
If you want any action on the button later you should set some commandargs to this button
(like the row index)

Here is some code (in vb)

in your aspx:
<asp:LinkButton runat=&quot;server&quot;
Text=&quot;Delete&quot;
CommandName=&quot;Delete&quot;
CausesValidation=&quot;false&quot;
id=&quot;but1&quot;
/>

in the code behind:
Private Sub ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles dgPlanner.ItemDataBound
Dim intRow As Int16 = e.Item.ItemIndex
Dim objDeleteBut As Button
If intRow > -1 Then
objDeleteBut = CType(e.Item.FindControl(&quot;but1&quot;), Button)
objDeleteBut.CommandArgument = e.Item.ItemIndex ' all buttons will have the same action but you need to know what row was clicked
objDeleteBut.Attributes.Add(&quot;onClick&quot;,&quot;....


You could use an asp:deleteColumn, some info on datagrids can be found here:



Greetings, Harm Meijer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top