How can I get access to the button from code behind using id "btnAutocomplete"?
<asp:GridView DataKeyNames="AutocompleteSchoolChild_Child" Width="1500px" CssClass="table table-bordered" OnDataBound="GridAutocomplete_OnDataBound"
ID="GridAutocomplete" runat="server" AutoGenerateColumns="false" AllowPaging="true" DataSourceID="sqlAutocomplete" Visible="true" PageSize="10"
OnSelectedIndexChanged="GridAutocomplete_OnSelectedIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-width="80px">
<ItemTemplate runat="server">
<asp:Button CssClass="btn btn-default" runat="server" ID="btnAutocomplete" Text="Зачислить" CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
...
I assume that you want to change button text in currently selected row, so that you need to use FindControl with GridViewRow instance & cast it to a Button control:
protected void GridAutocomplete_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridAutocomplete.SelectedRow;
Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");
btnAutocomplete.Text = "Insert"; // example to use button property
}
If you want to change button text in all GridView rows, you can use foreach loop together with GridViewRow instances on the same event handler:
foreach (GridViewRow row in GridAutocomplete.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");
btnAutocomplete.Text = "Insert"; // example to use button text property
}
}
If you're not sure that FindControl cast works properly, change all direct casts to as operator & use null checking like this:
GridViewRow row = (sender as GridView).NamingContainer as GridViewRow;
Button btnAutocomplete = row.FindControl("btnAutocomplete") as Button;
if (btnAutocomplete != null)
{
btnAutocomplete.Text = "Insert"; // example to use button text property
}
NB: The goal here is getting GridViewRow instance first before accessing button control inside TemplateField, so that SelectedRow is a proper way to get currently selected row.
Why don't you simply use GetElementById javascript method
document.getElementById("btnAutocomplete").innherHTML("");
Or jQuery:
("#btnAutocomplete").val = "";
As you've asked how to use this, I suggest that you add the code below after your HTML or your aspx layout code which you wrote in your question.
<script type="text/javascript">
//this function runs when the webpage is loaded
$(document).ready(function ()
{
document.getElementById("btnAutocomplete").innherHTML("whatever you want here");
//OR
("#btnAutocomplete").attr("style","whatever style html you want here");
});
//OR declare a private function which you can call through a click event
function buttonchange()
{
("#btnAutocomplete").val = "whatever value you want to give it";
}
</script>
You can assign the call event of the private function to some html element, for example:
<button type="button" class="btn" onclick="buttonchange()">Button changer</button>
i think you can define OnRowCommand for your gridview and define command name for your button,see this:
<asp:GridView DataKeyNames="AutocompleteSchoolChild_Child" Width="1500px" CssClass="table table-bordered" OnDataBound="GridAutocomplete_OnDataBound"
ID="GridAutocomplete" runat="server" AutoGenerateColumns="false" AllowPaging="true" DataSourceID="sqlAutocomplete" Visible="true" PageSize="10"
OnSelectedIndexChanged="GridAutocomplete_OnSelectedIndexChanged"
OnRowCommand="GridAutocomplete_RowCommand">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-width="80px">
<ItemTemplate runat="server">
<asp:Button CssClass="btn btn-default" runat="server" ID="btnAutocomplete" Text="Зачислить" CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
and in code behind:
protected void grdSms_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "select")
{
//do something
}
}
Related
I have a repeater that in it has one dropdown list and one linkbutton.
I want to get the selected value of the dropdown list by CommandArgument in linkbutton, but it just knows default value of dropdown list.
My code :
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Page_Load2"OnItemCommand="list_ItemCommand" >
<ItemTemplate>
<asp:DropDownList ID="dlPricelist" CssClass="width100darsad dropdownlist" runat="server" AutoPostBack="true" ViewStateMode="Enabled" >
</asp:DropDownList>
<asp:LinkButton ID="btnAddToCart" runat="server" class="btn btn-success btnAddtoCardSinglepage" CommandArgument='<%#Eval("id") %>' CommandName="addtocard">اضافه به سبد خرید</asp:LinkButton>
<asp:Label ID="xxxxxx" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load2(object sender, RepeaterItemEventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].ToString();
DataSet dsselectcategory = BLLTour.left3join(id.Trim().ToString());
var dlPricelist = (DropDownList)e.Item.FindControl("dlPricelist");
dlPricelist.DataSource = dsselectcategory.Tables[0];
dlPricelist.DataTextField = "pricelistPrice";
dlPricelist.DataValueField = "priceid";
dlPricelist.DataBind();
}
}
protected void list_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtocard")
{
foreach (RepeaterItem dataItem in Repeater1.Items)
{
Label xxxxxx = (Label)e.Item.FindControl("xxxxxx");
LinkButton btnAddToCart = (LinkButton)e.Item.FindControl("btnAddToCart");
xxxxxx.Text = ((DropDownList)dataItem.FindControl("dlPricelist")).SelectedItem.Text; //No error
}
}
}
I don't know how I should fix it.
You are using very old technology to show data that's not appropriate.
But if you are serious to use it, you must use FindControll method in ItemTemplate of your repeater control. You should find dropdownlist first, and then cast it to a object to be able to use it's value.
I am working on a project using Telerik controls. I'm trying to figure out how to get the selected row index on an ItemTemplate button click event, like in the markup below:
<telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True"
DataSourceID="cusGrid" GridLines="None" Skin="Default" AllowPaging="True" DataKeyValue="CustomerID"
PageSize="500" AllowMultiRowSelection="True" ShowStatusBar="true" >
<MasterTableView AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="cusGrid">
<RowIndicatorColumn>
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn>
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<Columns>
<telerik:GridTemplateColumn UniqueName="CheckBoxTemplateColumn">
<ItemTemplate>
<asp:Button runat="server" Text="Select" OnClick="SelRecord" />
</ItemTemplate>
</telerik:GridTemplateColumn>
...
Normally with a GridView I would just do something like:
protected void SelRecord(object sender, EventArgs e)
{
var gRow = (GridViewRow)(sender as Control).Parent.Parent;
var key = string.Empty;
if (gRow != null) { key = gRow.Cells[0].Text; }
}
What is the equivalent with the Telerik control?
Use the CommandArgument, and use OnCommand instead of OnClick to get the row index:
<asp:Button ID="Button1" runat="server" CommandArgument='<%#Container.ItemIndex%>' OnCommand="Button1_Command" ... />
Code-behind:
protected void Button1_Command(object sender, CommandEventArgs e)
{
GridDataItem item = RadGrid1.Items[(int)e.CommandArgument];
}
You can use CommandName="" instead of OnClick.
Also add onitemdatabound="RadGrid1_ItemDataBound" to the main telerik:RadGrid tag.
Then in the code behind:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
int selectedRowIndex = dataItem.RowIndex;
}
}
Looking through the Telerik documentation, it looks like you want:
var gRow = ((sender as Button).NamingContainer as GridItem).Selected;
You didn't ask about this piece, but I think this code:
if (gRow != null) { key = gRow.Cells[0].Text; }
is asking for trouble.
Although markup and code-behind are always highly coupled, directly referencing individual cells is a code smell if you ask me. I'm guessing that you want to pull "Select" out of the ASP Button in your ItemTemplate.
Can you assign an ID to your Button, and call FindControl("buttonID") to get the data you need? That will help keep your code more maintainable and readable.
<telerik:GridTemplateColumn UniqueName="IndexRow" HeaderText="#">
<ItemTemplate>
<%#Container.ItemIndex + 1%>
</ItemTemplate>
</telerik:GridTemplateColumn>
something like this in Button click event should work
foreach (GridDataItem item in RadGrid1.SelectedItems)
{
GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;
var key = string.Empty;
key = item.ItemIndex;
}
I have GridView with some of columns. all the columns are boundfield like:
<asp:BoundField DataField="orderId" HeaderText="orderId"
SortExpression="orderId"></asp:BoundField>
The last column is:
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="" onclick="LinkButton1_Click" Text="Button"></asp:LinkButton>
as you see , there is "onclick" with some method.. like:
lbltest.Text = gv_order.Rows[gv_order.SelectedIndex].Cells[2].Text;
With that code i get (offcourse) what i have on the selected row in cell number 2. how can i get value from the same row (and from cell number 2) where the button is clicked without the "selceted row" ? example: when i click button on row 2 - i get the cell 2 of that row.
That's possible?
If you want to retrieve 'orderid' in more clean way, you can use CommandName, CommandArgument properties and OnRowCommand event like this:
<asp:GridView (...) OnRowCommand="Gv_RowCommand" (...)>
...
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
CommandArgument='<%# Bind("orderId") %>' Text="Button"></asp:LinkButton>
and in code behind:
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int selectedOrderId = Convert.ToInt32(e.CommandArgument);
// ...
}
}
I hope this is what you want to do.
Edit - my answer to your comment:
Then, it's little more complicated and uses 'selectedRow' in some way. In my own code, I use this approach:
<asp:GridView ID="gv1" (...) DataKeyNames="orderId,email,username"
OnRowCommand="Gv_RowCommand" (...)>
...
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
CommandArgument='<%# DataBinder.Eval(Container,"RowIndex") %>' Text="Button">
</asp:LinkButton>
and in code behind:
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Select")
{
int orderId = Convert.ToInt32(gv1.DataKeys[selectedRowIndex]["orderId"]);
string email = gv1.DataKeys[selectedRowIndex]["email"].ToString();
// ...
}
}
I want to create a dynamic gridview with first row as drop down on clicking edit button. I dont have any idea on how to start. Can you please help. I have gone through some articals and found using the InstantiateIn method we can achieve.
public class CreateItemTemplate : ITemplate
{
//Field to store the ListItemType value
private ListItemType myListItemType;
public CreateItemTemplate(ListItemType item)
{
myListItemType = item;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//Code to create the ItemTemplate and its field.
if (myListItemType == ListItemType.Item)
{
TextBox txtCashCheque = new TextBox();
container.Controls.Add(txtCashCheque);
}
}
}
If you want to display this on a single page, you should not be creating a server control.
Use the grid's TemplateField.
Note: if you are using AutoGenerateColumns = true, just add the column to the grid markup. It will be added first.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList id="someId" runat="server">
<asp:ListItem Text="One" />
<asp:ListItem Text="twO" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
you may need to provide more information about what you want to do wth this drop down (does it need a default value?).
Based on your needs, you may be able to do this in markup, or, you may need to use a grid event.
Brian
UPDATE: adding event handler
if you set onrowcreated="GridView1_RowCreated" in the grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
onrowcreated="GridView1_RowCreated">
and do this in your code behind:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dropdown = e.Row.FindControl("someId") as DropDownList;
//dropdown.DataSource= <>; bind it
//dropdown.SelectedValue =<>"; / set value how you would
}
}
you can manipulate the drop down ad it gets created.
If it cannot fin the controls look in each cell: e.Row.Cells[[index]].FindControl(""someId"")
Ok... I have a database table called employees..
This has columns called ID, Name, datejoined and Cannotbedeleted (check boxes)...
Now i want to add a delete column which deletes the rows when clicked.
But there are some entries which cannot be deleted if the Cannotbedeleted field is true (checked)... so the delete button should be invisible for these rows.
Please tell me a way of how to do this...
<asp:CheckBoxField DataField="CannotBeDeleted" HeaderText="CannotBeDeleted"
SortExpression="CannotBeDeleted" />
<asp:BoundField DataField="TimeAdded" HeaderText="TimeAdded"
SortExpression="TimeAdded" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I also tried using in delete template field...
' >
But i did not know what to do in code behind??
protected bool GetShowDeleteButton()
{
}
The solution is below.... but is there a way i can refresh the page once i click the delete button in the gridview....
Try looping through the rows in GridView_DataBound, and hide the button for each row that has the checkbox checked.
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach(GridViewRow myRow in GridView1.Rows)
{
//Find the checkbox
CheckBox ckbox1 = (CheckBox)myRow.FindControl("nameOfCheckBox");
if(ckbox1.Checked)
{
//Find the Delete linkbutton and hide it
LinkButton deleteButton = (LinkButton)myRow.FindControl("nameOfDeleteLinkButton");
deleteButton.Visible = false;
}
}
}
Now, here's the difference you need:
Implement the CheckBox column as a TemplateField with a CheckBox in it. You can bind the CheckBox to the data from your datasource.
Do it like this:
if($row['cannotbedeleted'] == true) {
$buttonDisplay = 'none';
}
echo "<button onclick='delete();' style='display: $buttonDisplay;'>Delete</button>";
Well that would be the solution in PHP but if the style of the button has "display: none;" in it the button will be hidden. :) HTH