Get Value from ASP.NET GridView cell - c#

How would I get the value from a GrivView cell when the edit button is clicked?
I have tried other answer but none seem to work.
I would like to be able to get the value of Questionnaire ID for the row when the edit button is pressed.
Here is the gridview im working with.
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="edit" ShowFooter="true" FooterStyle-CssClass="view_table_footer">
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:TemplateField HeaderText="Results" HeaderStyle-Width="150px"></asp:TemplateField>
<asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="true" ItemStyle-CssClass="cart_delete">
</asp:CommandField>
</Columns>
</asp:GridView>
<asp:label ID="ab" runat="server"></asp:label>
The backend
protected void edit(object sender, GridViewEditEventArgs e)
{
string c = gvShowQuestionnaires.Rows[index].Cells[0].Text;
ab.Text = c;
}

The GridViewEventArgs has the index of the row being edited. It doesn't look like you are using the index from the event args. Try this:
protected void edit(object sender, GridViewEditEventArgs e)
{
string c = gvShowQuestionnaires.Rows[e.NewEditIndex].Cells[0].Text;
...
}

If you give your field an ID, you should be able to get it by calling
e.item.FindControl("fieldId").

Related

Passing gridview row data to textboxes on selection of gridview row

I can't seem to make data from my gridview pass to textboxes outside of my gridview on row selection. The event seems to be firing, but the textboxes are always filled with & nbsp;. I can't figure out why this is happening since none of the cells in the gridview are blank. I have been researching this problem for a few days, on this site and other sites, with no luck. Here is the piece of my aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtBLName.Text = GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text;
}
Here is my gridview code:
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
</asp:GridView>
Can someone please help? Thanks!
It's Working
ASP CODE
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView2"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
DataTable oDT = new DataTable();
oDT.Columns.Add("edit",typeof(string));
oDT.Columns.Add("LastName", typeof(string));
oDT.Rows.Add("ad", "1212121");
oDT.Rows.Add("aad", "1asdasd212121");
GridView2.DataSource = oDT;
GridView2.DataBind();
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
TextBox1.Text = row.Cells[1].Text;
}
RESULT

How to get value of a gridview cell in this scenario

I have a link button inside a gridView as below :
<asp:TemplateField HeaderText="Analyze">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Analyze" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
I have the LinkButton1_Click function as below :
protected void LinkButton1_Click(object sender, EventArgs e)
{
testtb.Text = name;
Console.WriteLine(name);
}
This variable "name" is the first column of the GridView.I am obtaining the value for "name" as below:
protected void UnanalysedGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView d = (DataRowView)e.Row.DataItem;
name = d["resultId"].ToString();
}
}
I want that on click of the link button the value of first column in that row of gridview becomes the text for the textbox testtb.
Somehow,the value for name remains null.
EDIT
I found out that probably RowDataBound isn't the correct event for my requirements because I need the value for each row.
So I removed the RowDataBound function.
I guess I have to handle this inside LinkButton1_Click itself.
I added this line to the function :
name = UnanalysedGV.SelectedRow.Cells[1].Text;
Still doesn't work.
Does anyone have any idea ?
You can do it using two approaches as mentioned below.
Handle click event of linkbutton through event bubbling code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging" OnRowCommand="grdCustomPagging_RowCommand">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("DealId") %>'
CommandName="VIEW">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCustomPagging_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "VIEW")
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string dealId = lnkView.CommandArgument;
}
}
Handle click event of linkbutton directly click event code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" OnClick="lnkView_Click">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void lnkView_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string rowNumber = grdrow.Cells[0].Text;
string dealId = grdrow.Cells[1].Text;
string dealTitle = grdrow.Cells[2].Text;
}
Hope this helps.

Get id from gridview

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="EmptyL" AllowPaging="True"
AllowSorting="True" GridLines="Vertical"
OnRowUpdating="TaskGridView_RowUpdating">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:CommandField ShowEditButton="True" />
<asp:CheckBoxField DataField="Status" HeaderText="Status" SortExpression="Status"/>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="EmptyLeg" runat="server"
ContextTypeName="Dev.Orpheus.App_Data.DataStorageDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
EntityTypeName="" OrderBy="Id desc" TableName="EmptyL">
</asp:LinqDataSource>
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label1.Text = ?????? updated ID ???????
}
Classical gridview data from linq
For example I update the field "Status"
How to get the ID of the updated object ?
You should get it in NewValues collection of GridViewUpdateEventArgs parameter
like this
e.NewValues["Id"]
for that you can use
<%# DataBinder.Eval(Container.DataItem, "Id") %>
method on CheckBoxField so that in
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label1.Text = //Chechbox value
}
and can update database or other filed as per necessary
Have a Good day.
Label1.Text = e.Keys[0]
The grid contains a primary .Keys property.

Accessing GridView data from a templatefield

<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1"
SortExpression="Field1" />
<asp:BoundField DataField="Field2" HeaderText="Field2"
SortExpression="Field2" />
<asp:TemplateField HeaderText="TemplateField1">
<ItemTemplate>
<asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
<asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnComplete_Click(object sender, EventArgs e)
{
String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
//I want to be able to access the row data do some computation and then be able to insert it into the database
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition.
}
Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.
You can do it like this:
protected void btnComplete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
//Alternatively you could use NamingContainer
//GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
Label lblComments = (Label)gvRow.FindControl("lblComments");
// lblComments.Text ...whatever you wanted to do
}
here is how you can access to the gridview row:
protected void btnComplete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvGrid.Rows)
{
Label lblComments = row.FindControl("lblComments") as Label;
....//you can do rest of the templatefiled....
}
}

Using C#, how to get one cell text from edited row?

Hy,
I have a gridView control in Asp.NET like this:
<asp:GridView ID="outputGridView" runat="server" onrowediting="OutputGridView_RowEditing">
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="250px" HeaderText="JobId" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<%# Eval("JobId")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="250px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
</aspGridView>
On OutputGridView_RowEditing I have this code:
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
string JobId = currentRow.Cells[2].Text;
e.Cancel = true;
}
But in 'JobId' string its "", does anyone have any idea how can I get the text of the third cell from the row that is being edited?
Thank you,
Jeff
Ok what Bonshington said is correct, accept you want to add an id to the label.
<ItemTemplate>
<asp:Label ID="LblJobId" runat="server" Text='<%# Eval("JobId") %>' />
</ItemTemplate>
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
Label jobIdLabel = (Label)currentRow.Cells[2].FindControl("LblJobId");
string jobId = jobIdLabel.Text;
e.Cancel = true;
}
Please use Bind() method instead of Eval() method, it is for evaluation purpose only.
try to put it in literal cotnrol
<label><%# Eval("JobId")%></label>
and your jobID column will positioned as cell's child control
if you want to get GridViewRow currentRow you have to use
<Columns>
<asp:TemplateField>
<EditItemTemplate><asp:Label id="lbl" Text="<%# Eval("JobId")%>" /></EditItemTemplate>
</asp:TemplateField>
</Columns>
Auto-generated grid columns use Cells property
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
OutputGridView.Rows[e.NewEditIndex].Cells[0]
}

Categories

Resources