How to get values of the gridview hidden fields in asp.net - c#

I am getting an error on accessing gridview hidden field Ids while trying to save the gridview row details. What i want to do is to save the all gridview rows back to database. I am bit confused on accessing the value of the row ids. Please help me to overcome this problem.
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ServiceID" Font-Names="Segoe UI Symbol" Font-Size="11pt" RowStyle-BackColor="#A1DCF2"
ShowFooter="true" Width="670px">
ForeColor="White" />
<PagerStyle CssClass="cssPager" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<%--ServiceID--%>
<asp:TemplateField HeaderText="ServiceID" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="lblServiceID" runat="server" Text='<%# Eval("ServiceId")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<%-- ServiceName --%>
<asp:TemplateField HeaderText="Service" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblService" runat="server" Text='<%# Eval("ServiceName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
//Save TestDetails
foreach (GridViewRow rw in GridView1.Rows)
{
var n = new TestDetail
{
PriceListId = txtPriceList.text,
ServiceId = Convert.ToInt32(GridView1.DataKeys[rw.RowIndex].Value),
Price = Convert.ToDecimal(txtPrice.Text.ToString()),
};
using (var context = new DiagEntities())
{
context.TestDetail.Add(n);
context.SaveChanges();
}
}

You should use the DataKeys:
// Get the index of the current row.
int index = rw.RowIndex;
// Based on the index of the row
// get the DataKey value and convert it to an int
ServiceId = Convert.ToInt32(GridView1.DataKeys[index].Value);

Related

asp net c# get value of specific row in gridview using checkbox

I have a gridview with three columns admin id, admin name and checkbox, and there is a single button below the gridview,
I want to get the value of admin name column and display it in a label when I check the checkbox and then click the button,
I tried doing this and its working fine but I can get one value only for example if I checked two checkbox and then clicked the button it get only the last value, and I want to get them all.
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="10"
AllowSorting="True" EnableViewState="false" width="863px" DataSourceID="SqlDataSource1" >
<Columns >
<asp:TemplateField HeaderText="req_id" >
<ItemTemplate >
<asp:Label ID="label_id" runat="server" Text='<%# Eval("admin_id") %>' ></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px" />
<HeaderStyle Width="30px" />
<FooterStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="admin_number">
<ItemTemplate >
<asp:Label ID="label_name" runat="server" Text='<%# Eval("admin_name") %>' ></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px" />
<HeaderStyle Width="60px" />
<FooterStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="privileges" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox_privileges" runat="server" Checked='<%# Convert.ToInt32(Eval("prev_1")) == 1 ? true : false %>' />
</ItemTemplate>
<ItemStyle Width="90px" />
<HeaderStyle Width="90px" />
<FooterStyle Width="90px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btn_save(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox_privileges") as CheckBox);
if (chkRow.Checked)
{
string name= (row.Cells[1].FindControl("label_name") as Label).Text;
Label4.Text = name;
}
}
}
}
In this line you are overriding the text:
Label4.Text = name;
To add all the text you should do something like this:
Label4.Text = name + Label4.Text;

Gridview value to a parameter

I have a Home.aspx and Home.aspx.cs
I have a gridview in my Home.aspx >>>
<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Height="281px" style="margin-top: 0px" Width="100%"
OnRowCancelingEdit="DataGridView_RowCancelingEdit"
OnRowEditing="DataGridView_RowEditing" OnRowUpdating="DataGridView_RowUpdating" HorizontalAlign="Center"
onrowdatabound="DataGridView_RowDataBound">
<AlternatingRowStyle BackColor="Lavender" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>Data 1</HeaderTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate><asp:Label ID="description" runat="server" Text='<%# Bind("description")%>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="Editdescription" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>SINGLE</asp:ListItem>
<asp:ListItem>DOUBLE</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<%-- <FooterTemplate>
</FooterTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Data 2</HeaderTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate><asp:Label ID="pkgcode" runat="server" Text='<%# Bind("pkgcode") %>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="Editpkgcode" runat="server" Text='<%# Bind("pkgcode") %>'></asp:TextBox></EditItemTemplate>
<%--<FooterTemplate><asp:TextBox ID="pkgcode" runat="server"></asp:TextBox></FooterTemplate>--%>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Data 3</HeaderTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate><asp:Label ID="oprcode" runat="server" Text='<%# Bind("oprcode") %>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="Editoprcode" runat="server" Text='<%# Bind("oprcode") %>' ></asp:TextBox></EditItemTemplate>
<%--<FooterTemplate><asp:TextBox ID="oprcode" runat="server"></asp:TextBox></FooterTemplate>--%>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my Home.aspx.cs, I have this >>
protected void DataGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{ }
This is where I plan to update my data from my gridview, but before updating I want to pass the old data to a parameter so user can compare/see the changes he made. For checking purposes so I can see if it really get the data, I put the following inside DataGridView_RowUpdating (and I don't know if it's wrong)>>
GridViewRow row = DataGridView.Rows[e.RowIndex];
string #editpkgcode = (row.FindControl("pkgcode") as Label).Text;
Literal1.Text = "TEST: " + #editpkgcode;
It gives me the error : NullReferenceException was unhandled by user code
The reason why you get NullReferenceException is because when RowUpdating event fires then the EditItemTemplate exists but not ItemTemplate.
Since you defined pkgcode Label in ItemTemplate, therefore this label control is not existing when RowUpdating event fires. But, because the EditItemTemplate exists when this event fires, so you can access the Editpkgcode textbox defined in EditItemTemplate.
Therefore, you should be using the following code in your RowUpdating event in order access the textbox in EditItemTemplate.
GridViewRow row = DataGridView.Rows[e.RowIndex];
string #editpkgcode = (row.FindControl("Editpkgcode") as TextBox).Text;

Unable to get data from TextBox/DDL in Gridview

I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;

how to show values from database in a dropdownlist which is inside a gridview?

I'm trying get values from database to dropdownlist which is placed inside a gridview item template. I'm using gridview to take values from user. In one column I'm using dropdownlist from which user has to select an item. According to the selection its cost price will populate automatically on the other column. But I'm unable to get the values in dropdownlist and getting an error "Object reference not set to an instance of an object."
Aspx code given below:
<asp:GridView ID="gvItemList" runat="server" ShowFooter="True" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" ViewStateMode="Enabled" CssClass="newStyle9" style="text-align: center" OnRowDeleting="gvItemList_RowDeleting" OnRowDataBound="gvItemList_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sl No" SortExpression="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server"
Text='<%# Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="128px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Date">
<ItemTemplate>
<asp:TextBox ID="txtRequiredDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="txtRequiredDate_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtRequiredDate">
</ajaxToolkit:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Required Quantity">
<ItemTemplate>
<asp:TextBox ID="txtRequiredQuantity" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost Price">
<ItemTemplate>
<asp:Label ID="lblCostPrice" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UoM Code">
<ItemTemplate>
<asp:Label ID="lblUomCode" runat="server">Manual</asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="AddRowButton" runat="server" Text="Add New Item"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code under row databound is given below:
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
DS_SiteDataTableAdapters.tbl_ItemTableAdapter item;
item = new DS_SiteDataTableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItem();
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
ddlItem.DataSource = dt; //here I'm getting an error "Object reference not set to an instance of an object."
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
}
Any help is greatly appreciated!
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Select Country"));
}
Hope this helps!
just check below condition in your method
if (e.Row.RowType == DataControlRowType.DataRow)
{ your code }
I hope it will help u
As mentioned in the comments, you are trying to use a null object, thinking that it has a referenced object.
You are doing something like this:
public class Example
{
public void MyMethod()
{
}
}
Example myExample= null;
myExample.MyMethod();
You will get "Object reference not set to an instance of an object." which is the same as NullReferenceException because you are calling a method on a reference type which is null.
You are getting Object Reference error because you are not checking for DataRow in your gridview. Because of that it is trying to find the dropdown in header where it is not present and thus you are getting Dropdown object as Null.
Add this condition to your gvItemList_RowDataBound event:-
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Your rest code
}
}
try this you get null reference because you are not able to find ddlItem control
at line
DropDownList ddlItem = (DropDownList)e.Row.FindControl("ddlItem");
so instead you can try as below
DropDownList ddlItem = (DropDownList)GridView.Rows[rowindex].FindControl("ddlItem"))

Show Footer row as a first row in gridview

I have a footer template in my gridview which allows users to add new items to the grid. Since they don't want to go below the page each time to add and they want to bring that footer row as the first row of the gridview.
ASPX:
<asp:GridView ID="gvApplication" runat="server" AutoGenerateColumns="False" HorizontalAlign="center"
ShowFooter="True" CellPadding="3" GridLines="Both" CssClass="contentfont" ShowHeaderWhenEmpty="True"
EmptyDataText="No Records Found" OnRowDataBound="gvApplication_RowDataBound"
OnRowDeleting="gvApplication_RowDeleting" OnRowCommand="gvApplication_RowCommand"
DataKeyNames="ID,Group,App_Name" Width="100%">
<Columns>
<asp:TemplateField HeaderText="ID"
<asp:Label ID="lblID" runat="server" Text='<%# Bind("[ID]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlID" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlID_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Application Group">
<ItemTemplate>
<asp:Label ID="lblAppGrp" runat="server" Text='<%# Bind("[Group]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlGroup" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Application Name">
<ItemTemplate>
<asp:Label ID="lblAppName" runat="server" Text='<%# Bind ("[App_Name]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlApp" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlApp_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/delete.gif"
ToolTip="Delete" OnClientClick="return confirm('Are you sure want to Delete');" />
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" Width="65px" runat="server" CausesValidation="False"
CommandName="AddNew" Text="Link Code" ForeColor="#3f6da2" Font-Bold="true">
</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Wrap="False" />
<HeaderStyle Wrap="False" BackColor="#5B95CF" ForeColor="White" Height="25px" BorderStyle="Ridge" />
<FooterStyle BackColor="#D1DDF1" ForeColor="White" Font-Bold="True" />
</asp:GridView>
CS:
public void gvApplication_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drview = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlID = (DropDownList)e.Row.FindControl("ddlID");
ddlID .DataSource = AppDataRepository.GetID();
ddlID .DataValueField = "ID";
ddlID .DataTextField = "ID";
ddlID .DataBind();
ddlID .Items.Insert(0, new ListItem("--Select ID--", "0"));
ddlID .SelectedIndex = 0;
DropDownList ddlGroup = (DropDownList)e.Row.FindControl("ddlGroup");
ddlGroup.DataSource = AppDataRepository.GetGroup();
ddlGroup.DataValueField = "Group";
ddlGroup.DataTextField = "Group";
ddlGroup.DataBind();
ddlGroup.Items.Insert(0, new ListItem("--Select Group--", "0"));
ddlGroup.SelectedIndex = 0;
DropDownList ddlApp = (DropDownList)e.Row.FindControl("ddlApp");
ddlApp.DataSource = AppDataRepository.GetApp();
ddlApp.DataValueField = "App_Name";
ddlApp.DataTextField = "App_Name";
ddlApp.DataBind();
ddlApp.Items.Insert(0, new ListItem("--Select App--", "0"));
ddlApp.SelectedIndex = 0;
}
}
Try with HeaderTemplate
<asp:TemplateField HeaderText="ID"
<asp:Label ID="lblID" runat="server" Text='<%# Bind("[ID]") %>'></asp:Label>
</ItemTemplate>
<HeaderTemplate>
<asp:DropDownList ID="ddlID" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlID_SelectedIndexChanged" />
</HeaderTemplate>
</asp:TemplateField>
add FooterStyle-HorizontalAlign="Right" to the parent column of the template
Since Internet explorer dropped support for css top:expression - I have had to separate gridview headers into a separate table.
I have a table. In the first row / first cell I put another table containing the table headers.
In the next row / first cell I have a div set to be 20px wider than the table above (to allow for scroll bar on div). The div contains the gridview with no header. In the pre_render of the gridview I set the widths of the columns in both tables.
I spend a bit of time checking the size of the user screen etc and setting widths for the the tables / div (and a height for the div). The result is a table with static headers which are exactly the same width as the gridview below. You could easily do this and add an extra row in the header table to contain the controls that are currently in the footer row of the gridview.

Categories

Resources