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();
// ...
}
}
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.
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
}
}
I have a GridView in a ASP.NET web application, in which I have added image button in each row:
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="edit" runat="server" CommandArgument='<%# Bind("EmpID") %>' CommandName="edituser" ImageUrl="image/images.jpg"
ToolTip="Edit User Details"> </asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
Now how I can get the row data from gridview simply by clicking an edit image button in a row?
You have to change the CommandArgument with this one:
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>
Then:
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "edituser") /*if you need this
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the buttonfrom the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here now you have the specific row data
}
}
Bind all the columns in the label control respectively, and you can get value using findcontrol method at GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Label _lblText = (Label)this.GridView1.SelectedRow.FindControl("UR_Desired_Label_ID");
this.TextBox3.Text = _lblText.Text ;
}
It seems like this would be simple, but for the life of me, I can't figure out how it would work.
I have a gridview.
I have a standard button.
How do I use the button click to display the gridview?
Any suggestions?
This is a brief example from the MSDN page: (https://msdn.microsoft.com/en-us/library/bb907626.aspx)
You might to add an asp:TemplateField inside your GridView and through the CommandArgument property in the Button, set the current row index.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
And in your code, in the RowCommand event:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "AddToCart") {
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
Hope this help you.
Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you