Get id from gridview - c#

<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.

Related

Delete GridView Rows in button cick without RowDeleting that not saved in DB

I have a gridview,
When Button ADD is clicked the textboxs values will be added to gridview.
After adding values to gridview i want to select a row and click delete button but error occurs to me on deleting.
My GridView Code
<asp:GridView ClientIDMode="Static" ID="GridPesonal" runat="server" AutoGenerateColumns="False" Class="GrdSty" Width="100%" DataKeyNames="RowNumber">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="ردیف">
</asp:BoundField>
<asp:BoundField DataField="StartDate" HeaderText="از تاریخ">
</asp:BoundField>
<asp:BoundField DataField="EndDate" HeaderText="تا تاریخ">
</asp:BoundField>
<asp:BoundField DataField="SherkatName" HeaderText="نام شرکت،سازمان یا موسسه" >
</asp:BoundField>
<asp:BoundField DataField="WorkUnitName" HeaderText="واحد محل کار">
</asp:BoundField>
<asp:BoundField DataField="Sharh" HeaderText="شرح دقیق شغل/سمت/مسئولیت" >
</asp:BoundField>
<asp:BoundField DataField="WorkTime" HeaderText="زمان کار" >
</asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="توضیحات">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SavabegSelect" runat="server" AutoPostBack="True" OnCheckedChanged="SavabegSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
موردی ثبت نشده است.
</EmptyDataTemplate>
</asp:GridView>
Btn Delete Code
<asp:Button ClientIDMode="Static" ID="BtnDelete" CssClass="btnregister" runat="server" Text="حذف" OnClick="BtnDelete_Click" />
Code behind of btn Delete
protected void BtnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridPesonal.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("SavabegSelect");
if (chkdelete.Checked)
{
GridPesonal.DeleteRow(gvrow.RowIndex);
}
}
}
When execute above code this error show
The GridView 'GridPesonal' fired event RowDeleting which wasn't handled.
Have you used command-name as Delete on BtnDelete.
Remove that from Delete Button it will work.
If you have like this
<asp:GridView ID="gvRoute" DataKeyNames="Route" runat="server" AutoGenerateColumns="false"
AllowPaging="true" Width="30%"
onrowdeleting="gvRoute_RowDeleting">
Remove onrowdeleting="gvRoute_RowDeleting
or wirte event for
protected void gvRoute_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
\\
}
or Use the "CommandName" property "Delete"
Or Use OnClick
<asp:GridView ClientIDMode="Static" ID="GridPesonal" runat="server" AutoGenerateColumns="False" Class="GrdSty" Width="100%" DataKeyNames="RowNumber" OnClick="BtnDelete">

How to fetch primary key in GridView but don't display it?

Using <asp:GridView></asp:GridView> I am trying to display columns of database table. I want to fetch primary key of table but obviously don't want to display it. How can I achieve this?
This is my GridView
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" AllowPaging="false" PageSize="5" AllowSorting="true" AutoGenerateColumns="false"
AutoGenerateEditButton="true" OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true" OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value" BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
I also tried visible=false to hide primary key, it hides primary key from displaying but also don't fetch its value and I want this value.
Hope my question is clear.
You need to set Visible = false within the OnRowDataBound event, this will mean the data is still accessible to you, but won't display on the page.
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF"
AllowPaging="false" PageSize="5" AllowSorting="true"
AutoGenerateColumns="false" AutoGenerateEditButton="true"
OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true"
OnRowDeleting="MyGrid_RowDeleting"
OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value"
BorderWidth="0px" BorderStyle="Solid">
<Columns>
<asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
<asp:BoundField DataField="Column1" HeaderText="Column1" />
<asp:BoundField DataField="Column2" HeaderText="Column2" />
<asp:BoundField DataField="Column3" HeaderText="Column3" />
</Columns>
</asp:GridView>
In Codebehind:
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
<asp:GridView ... DataKeyNames="PrimaryKey" />
You can use this:
<asp:BoundField DataField="PrimaryKey" visible="false" HeaderText="PKId"/>
Also use this
<asp:BoundField DataField="PrimaryKey" visible="false" HeaderText="UserId"/>
To get Primary Key
<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" DataKeyNames="PrimaryKey"
MyGrid.DataKeys[e.NewEditIndex].Value
OR
MyGrid.Rows[e.NewEditIndex].DataBoundItem
If you want to hide a column by its name instead of its index in GridView. After creating DataTable or Dataset, you have to find the index of the column by its name then save index in global variable like ViewStae, Session and etc and then call it in RowDataBound, like the example:
string headerName = "Id";
DataTable dt = .... ;
for (int i=0;i<dt.Columns.Count;i++)
{
if (dt.Columns[i].ColumnName == headerName)
{
ViewState["CellIndex"] = i;
}
}
... GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer)
{
int index = Convert.ToInt32(ViewState["CellIndex"]);
e.Row.Cells[index].Visible = false;
}
}

nested gridview get parent row

I am using Nested GridViews where each row in the gridview has child gridView.
I am using RowDataBound Event of Parent GridView, to Binding Child GridView.
My Problem is that, how to get Parent GridView's Key on Child gridViews RowDataBound Event.
Below is example code:
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="1" AllowPaging="true" PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" SkinID="GVCenter" onrowdatabound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the code behind:
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvChild= (GridView)e.Row.FindControl("gvChild");
gvChild.DataSource = getChildObj();
gvChild.DataBind();
}
}
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Here I need to get the parent gridview Row Key
}
}
Hope the above code explains all the scenario.
Thanks in advance
Sandy
Try this
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="10" AllowPaging="true"
PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" OnRowDataBound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HdnID" runat="server" Value='<%# Eval("ID") %>' />
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false"
ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvChild = (GridView)e.Row.FindControl("gvChild");
gvChild.DataSource = GetData();
gvChild.DataBind();
}
}
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = ((HiddenField)e.Row.Parent.Parent.Parent.FindControl("HdnID")).Value;
}
}
I don't think you will be able to track it normally, but I would embed ID field into the hidden field and put this hidden field under TemplateField,
<ItemTemplate>
<asp:HiddenField ID="idOfYourHiddenField" runat="server" Value='<%# Eval("ID") %>' />
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
</Columns>
</asp:GridView>
</ItemTemplate>
this way you can get its value by going
gvChild.Parent.FindControl("idOfYourHiddenField");
You Can Access The Parent of Child Gridview with the Parent Property.
You must be Try This:
GridView gvChild = (GridView)e.Row.FindControl("gvChild");
Response.Write(gvChild.Parent);
You have to go 4 steps back and get the parent row like this
protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvMasterRow = (GridViewRow)e.Row.Parent.Parent.Parent.Parent;
}
}
<asp:GridView ID="gvParent" DataKeyNames="ID" runat="server" PageSize="1" AllowPaging="true"
PagerSettings-Mode="NextPrevious" AutoGenerateColumns="False" SkinID="GVCenter"
OnRowDataBound="gvParent_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvChild" DataKeyNames="ID" runat="server" AutoGenerateColumns="false"
ShowHeader="false" OnRowDataBound="gvChild_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# (((IDataItemContainer)Container.Parent.Parent.Parent).DataItem as MyClass).MyProperty %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>

Get Value from ASP.NET GridView cell

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").

Accessing data from a BoundField of Gridview

I have a GridView like this
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>
Now when I click on the download Button, how can I get the corresponding f_Id in order to get the related data from Database.
This code should work, tested on my local.
First, add DataKeyNames to your GridView.
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_Id">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>
Then, access DataKeys from codebehind.
protected void gv_FilesList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
//row index
int index = Convert.ToInt32(e.CommandArgument);
//retrieve f_Id
int f_Id = Convert.ToInt32(gv_FilesList.DataKeys[index].Value);
//download file with f_Id
DownloadFile(f_Id);
}
}
A couple of ways to skin it, but you could access it like below:
void gv_FilesList_RowCommand(Object sender, GridViewCommandEventArgs e) {
if(e.CommandName=="DownloadFile")
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_FilesList.Rows[index];
string fileDownloadId = row.Cells[1].Text;
//Pull from DB
}
And then add f_id, to the DataKeyNames attribute so it will store the hidden fields value.
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_id">
DataKeyNames
A solution to your problem is described in this thread.
Basically you can access the row index in the event argument property called CommandArgument.

Categories

Resources