I have a GridView with Textboxes inside, one for each row.
I need change the attribute "onkeypress" to validate keys.
<asp:Table runat="server">
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:GridView ID="gridview_1" DataSourceID="SqlDataSource3" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="textbox">
<ItemTemplate>
<asp:TextBox ID="textbox_1" CssClass="textbox_1" runat="server" Text='<%# Eval("sql_textbox")%>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:TableCell>
</asp:TableRow>
And in the code behind:
foreach (GridViewRow row in gridview_1.Rows)
{
TextBox txtbox = ((TextBox)gridview_1.Rows[row.RowIndex].FindControl("textbox_1"));
txtbox.Attributes.Add("onkeypress","javascript:return validateFloatKeyPress(this, event);");
}
But when textboxes are generated, the JavaScript doesn't work. Why?
I can't do it in the ASP part, because I want the textboxes have different JavaScript methods with "if" clause in the code behind.
Thank you very much.
I put in asp:GridView the attribute onrowdatabound="GridView1_RowDataBound" and seems works properly. In code behind, I put...
<asp:GridView ID="gridview_1" DataSourceID="SqlDataSource3" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound" runat="server">
In code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
TextBox textBox1 = e.Row.FindControl("textbox_1") as TextBox;
textBox1.Attributes.Add("onkeypress","javascript:return validateFloatKeyPress(this, event);");
}
}
And it works properly, I think :)
Related
Hello Respected sirs,
I am generating a shopping cart like ordering system, in which i add/bind the productname, productprice, and productquantity from DataTable to GridView.
I have Added an ImageButton to the gridview only for deleting the selected row.
I also know that we can not delete a row from a dynamically generated grid view. so i placed a code in the ImageButton Click event that deletes the row from DataTable (Which is STATIC during the whole process) and again binds the Data With GridView.
Please note that i hv already once bind the data with gridview in my "BTN_ADD TO CART_Clicked".
Here is my code snippet,
protected void gvorderlist_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
DataRow row = dt.Rows[index];
dt.Rows.Remove(row);
gvorderlist.DataSource = dt;
gvorderlist.DataBind();
}
}
and ASP code is,
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am getting an Error which says : The GridView 'gvorderlist' fired event RowDeleting which wasn't handled.
Any help will be appreciated...
Thank You
The error explains everything. You need todefine the event method for OnRowDeleting in markup:
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand" OnRowDeleting="gvorderlist_RowDeleting">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And add an empty method in the code:
protected void gvorderlist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// No need to implement code here
}
The attributes for the GridView are case-sensitive, so change onrowcommand to OnRowCommand and see if that fires when you click the delete button. If not, you'll need to define OnRowDeleting explicitly. (Also change the capitalization of onpageindexingchange)
Give Command Name=D instead of Delete. It searches for Row_Deleting event when Command Name =Delete.
I Have a LinkButton In a TemplateField In a GridView. The LinkButton is bound to database which shows the time save in database.All I want is to fetch each linkbutton time value and compare it to current time and if linkbutton time is less than current time ,make it disable.
Any pointers will be helpful.
Thanks in advance.
<asp:GridView ID="grdview" AutoGenerateColumns="false" runat="server" OnRowCommand="grdview_RowCommand">
<Columns>
<asp:BoundField DataField="AudiName" DataFormatString="Audi {0}" HeaderText="Audi Name" />
<asp:TemplateField HeaderText="StartTime">
<ItemTemplate>
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
CommandName="time"
CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
<asp:HiddenField runat="server" ID="hf1" Value='<%#Eval("StartTime")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use the OnRowDataBound event to hook into the data binding and disable the button.
Form
<asp:GridView ID="MyGridView"
OnRowDataBound="MyGridView_RowDataBound"
runat="server">
....
</asp:GridView>
CodeBehind
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the button
var linkButton = (LinkButton) e.Row.FindControl("MyLinkButton");
// Toggle enabled/disabled based on time
// Using the button text is probably a bad idea, but is used here for demonstration purposes
linkButton.Enabled = (Convert.ToDateTime(linkButton.Text) > DateTime.Now);
}
}
The code above has not been tested, but should give you an idea of how you can approach this.
You can set the Enabled property of LinkButton comparing with the current time:
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
Enabled = '<%# ((DateTime)Eval("StartTime")< DateTime.Now )? false : true %>'
CommandName="time" CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="MatrĂcula" runat="server" Text="MatrĂcula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.
I have problems with binding a value of a field inside a gridview to a textbox which is inside the gridview as well. I'm intending to do this for editing the table.
I tried to do this with eval and bind, but the textbox won't show the values and I have absolutely no clue why.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Eval("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
The thing is that it works fine inside the ItemTemplate, but doesn't inside the EditItemTemplate-element. Really no clue what the problem is.
Code behind:
Sub gvBS_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles gvBS.RowEditing
gvBS.EditIndex = e.NewEditIndex
End Sub
Sub gvBS_RowCancelingEdit() Handles gvBS.RowCancelingEdit
Me.gvBS.EditIndex = -1
gvBS_DataBind()
End Sub
I assume that the GridView enters never edit-mode since you aren't handling the RowEditing event or you didn't DataBind it after you've set gvBS.EditIndex = e.NewEditIndex;.
<asp:GridView
OnRowEditing="gvBS_RowEditing" OnRowCancelingEdit="gvBS_RowCancelingEdit"
ID="gvBS" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" SkinID="gvWithoutWidth">
codebehind (BindGrid is the method which databinds your grid):
protected void gvBS_RowEditing(object sender, GridViewEditEventArgs e)
{
gvBS.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void gvBS_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvBS.EditIndex = -1;
BindGrid();
}
You should also remember to databind it only on the first load, not on consecutive postbacks when ViewState is enabled(default). Therefore you can check the page's IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
Try the Bind instead of Eval in EditItemTemplate like this
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Bind("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
I've got an asp:DataGrid which has an asp:Gridview within it and this has many nested asp:Repeater's within that and i'm trying to reference the nested repeater from within my OnItemDataBound function
My code is similar to this
<asp:Datagrid runat="server" id="DataGrid1" OnItemDataBound="ItemDB" AutoGenerateColumns="false" Gridlines="None">
<Columns>
<asp:TemplateColumn HeaderText="">
<ItemTemplate>
<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<p>Test</p>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:Datagrid>
bit complicated but that's kinda what i'm working with.
In my ItemDB command I have this
Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
If CType(e.Item.FindControl("GridView1"), GridView).Visible = True Then
CType(e.Item.FindControl("Repeater"), GridView).Visible = True
End If
End If
End Sub
but i get the error
Object reference not set to an instance of an object
and i'm guessing it's because i am referencing a Repeater within a GridView
Any ideas how to reference this properly?
This code may not be the simplest way of doing this but i've taken over someone else's work and need a quick fix before re-coding it all
Thanks in advance
You'll have to find the Gridview in the template and then register the event for it's RowDataBound, and the find the repeater in the event handler. You should use the OnItemCreated Event to register the OnItemDataBound events, but the easiest would be to indicate the methods in your .aspx:
<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater id="Repeater1" runat=""server"
onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<p>Test</p>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in your code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//you could find the repeater in the gridview's itemtemplate here
// to the BulletedList
if (e.Row.RowType == DataControlRowType.DataRow)
{
Repeater rpt = (Repeater)e.Row.FindControl("Repeater1");
rpt.Visible = false;
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//you could find controls in the repeater's itemtemplate here.
}