writing code in button's click event in gridview - asp.net

i have added a button control in gridview and i want to redirect
to the another page on button's click event,
and also i want to access the values of selected row in a gridview and show that values on other page on button
click event which is inside the gridview,, can anybody plz help me out in this .

this should be helpful: http://msdn.microsoft.com/en-us/library/bb907626.aspx
for accessing values inside RowCommand event find your row first (by index):
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = MyGridView.Rows[index];
and then controls inside it which holds the values you need:
Label MyLabel= (Label)row.FindControl(MyLabel);
after that all you need to do is to transfer to your page and send values from your controls with it (do that with querystring):
Server.Transfer("MyPage.aspx?value="+MyLabel.Text)
here you can read more about gridview RowCommand event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

You need to add either a ButtonField or a TemplateField with a button inside and then you can add your code to the RowCommand and use the e.CommandName and e.CommandArgument
To redirect you can use Response.Redirect(address)
To see the values it depends where in the program you want to do it. If during databinding you can use the dataitem("column"). Outside of databinding you can go through the Gridview.Rows collection for the row you want and then look at the row.Cells(columnNumber).Text to see the value.

we have an event in gridview called, gridview rowcommand event, in that you can write the code for redirecting to another page using button. First you have to bind the value of which you want to pass in button property called commandargument.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("abc.aspx?id=" + e.CommandArgument);
//here id means passing the value using querystring to another page.
}

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name" DataField="fullname" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClick="btnDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// This focuses the current row where the button lies. you can perform all events of server-controlls
//instead of Button e.g LinkButton, Dropdownlist index changes...
protected void btnDelete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
string id = gvRow.Cells[0].Text;
string name = gvRow.Cells[1].Text;
//use these values in query string or any logic you prefer for cross page posting
Response.Redirect("your URL ?id=" + id + "&name=" + name);
}

Related

select data from gridview field and populate textbox

I'm trying to populate a single text box (or parameter) with data from a gridview column when I click on a button in that row.
Gridview gets it data from a sqlconnection
the gridview is
| Drawing |
| 12345 | VIEW
| 12346 | VIEW
the VIEW is a template button with an onclick event, when the user clicks the button the data from the Drawing column (12345) should be passed to ether a textbox or a paremeter. (this is the part I dont know how to do) once the Iv got the number in a textbox I can use it as pareameter and then a pdf is opened of that drawing, I have code for this and is working.
thanks for any help
If you are using C#, the simplest thing to do would be to add an in-built select command button to the gridview rows at runtime. Then on the selectedindexchanged event of the gridview simply access the cell of the selected row that you want the value from. You can then assign that string to anything you want. Like so:
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string myString = myGridView.SelectedRow.Cells[4].Text.ToString();
TextBox1.Text = myString;
}
Remember that the cell index collection is zero based, so [0] is actually the first cell in the row.
Use TemplateFields and the grid view's OnRowCommand event, like this:
Markup:
<asp:gridview id="GridView1"
OnRowCommand="GridView1_RowCommand"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxDrawing" runat="server"
Text="<%# Eval("Drawing")) %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="selc" runat="server" Text="View"
CommandName="View"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked
if(e.CommandName == "View")
{
// Convert the row index stored in the CommandArgument
// property to an integer
var index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection
var row = GridView1.Rows[index];
// Find the drawing value
var theDrawingTextBox = row.FindControl("TextBoxDrawing") as TextBox;
// Verify the text box exists before we try to use it
if(theDrawingTextBox != null)
{
var theDrawingValue = theDrawingTextBox.Text;
// Do something here with drawing value
}
}
}

Determine the datatable index of the row clicked in GridView

I have a GridView in ASP.NET page. The GridView is bound to a dataset/datatabe. One of the columns of the grid is a command button and the gridview has method OnRowCommand (e.g. OnRowCommand="GridView_RowCommand") specified.
When user clicks on the button in the grid, the method GridView_RowCommand fires. I would like to find the index to the DataTable for the row where button was clicked. Note, that I am not looking for index to the GridView row but rather the index to the DataTable bound to the GridView.
Thank you in advance for your help.
You have a few options and it depends on the amount of data you are binding to the gridview, one you could save the dataset/datatable to Session[""] as you bind or you could retrieve the data from the database again once you have the unique id of the row. You could create the following on your gridview:
<asp:GridView ID="gvCustomer" runat="server"
AutoGenerateColumns="False" DataKeyNames="yourId" onrowcommand="gvCustomer_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkAction" runat="server" Text="Do Something" CommandName="yourEvent" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then in the code behind for the RowCommand event have:
protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "yourEvent")
{
var row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int rowId = Convert.ToInt32(gvCustomer.DataKeys[row.RowIndex]["yourId"]);
}
}
At this point you have the id which you could either query the database again or access the data source object that you save in to session before binding to the gridview
Or another alternative is:
<asp:LinkButton CommandArgument='<%#Eval("PrimaryKey")%>' />
Then you can get the arg with e.CommandArgument in the gvCustomer_RowCommand method

open of popup on click of gridview linkbutton

I have Gridview and ,it consists of 3 columns , the 1st column is of ID,2nd of date and 3rd of description.
the 1st column ID's are all linkbutton and when i click the linkbutton a popup window has to open.
and the text of the linkbutton should be populated in the textbox of popup window. plz help me
Add a hyperlink column to your grid view, pass the text as query string to the pop up page, don't forget to set target property to _blank.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="AnyText"
DataNavigateUrlFormatString="Page.aspx?text={0}"
DataTextField="AnyText" HeaderText="Test" Target="_blank" />
</Columns>
</asp:GridView>
On page.aspx you need to place a textbox then in page load event add:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = Request.QueryString["text"];
}
Hope this is what are you looking for.

how to access templatefield from code behind

the reason why i am looking to update dynamic is because i am using objectdatasource and my objectdatasource have a collection of object and within that object i have another object that i wanted to access so for an example:
+Student
......
......
......
-Courses
.........
.........
Name
Update end
how do i bind templatefield from code-behind?
<asp:Gridview ID="gridview1" runat="Server">
<columns>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:Gridview>
First of all define your key field in GridView control, just add net attribute to GridView markup: datakeynames="StudentID".
You can use both event handler for GridView: RowDataBound or RowCreated. Just add one of this event handler and find there control that is placed in your ItemTemplate. Like here, for instance:
void ProductsGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the LinkButton control from the first column.
Label someLabel = (Label)e.Row.FindControl("someLabel");
if (someLabel != null)
{
// Get Student index
int StudentId = (int)GridView.DataKeys[e.Row.RowIndex].Values[0];
// Set the Label Text
// Define here all the courses regarding to current student id
someLabel.Text = //
}
}
}
This example was gotten from MSDN
Here are some code samples from MSDN:
http://msdn.microsoft.com/en-us/library/aa479353.aspx
These are in VB but you should be able to locate C# also :-)
If you follow this link and scroll down you will find a code sample:
http://bytes.com/topic/asp-net/answers/624380-gridview-generated-programmatically

give the ID as a custom attribute to checkbox in a grid for manual update

I like to update just the value of my checkbox in a asp grid.
so i thought i bind the id to the checkbox ( but how?) and fire an update in code behind by clicking the checkbox.
but how can I get the ID, and where I have to bind this id to get it in code behind in the event?
Thanks
Here is what I've managed to do. (Be aware there should be an easier way to do this. I'm very new to ASP.NET)
Here you have a TemplateField in a GridView. Inside it there is an UpdatePanel and the CheckBox is inside it. This is done to make the checking of the TextBox do post in the backgroung (ajax). You might not need it (UpdatePanel) at all.
<asp:TemplateField HeaderText="Private" SortExpression="IsPrivate">
<ItemTemplate>
<asp:UpdatePanel ID="upIsPrivate" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:CheckBox ID="chkIsPrivate" runat="server" OnCheckedChanged="chkIsPrivate_CheckedChanged" AutoPostBack="true" />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
And this is the method that handles this. Notice that I get the Id from the GridViewRow that contains the CheckBox:
GridViewRow row = (GridViewRow)((CheckBox)sender).Parent.Parent.Parent.Parent;
protected void chkIsPrivate_CheckedChanged(object sender, EventArgs e)
{
if (editMode)
{
GridViewRow row = (GridViewRow)((CheckBox)sender).Parent.Parent.Parent.Parent;
Int32 id = (Int32)uxPhoneCallList.DataKeys[row.RowIndex]["Id"];
CheckBox isPrivate = (CheckBox)row.FindControl("chkIsPrivate");
PhoneCall phoneCall = PhoneCallManager.GetById(id);
...
}
}

Resources