I am trying to nest one gridview within another, but I cannot get the data to populate in the second grid view. I am getting an error when trying to set the data source of the second data grid (saying it is null). Can anyone help?
Here is the aspx page:
<div id="divSource" runat="server" align="center">
<asp:GridView ID="Source" runat="server" AutoGenerateColumns="False" DataKeyNames="sourceLineItem" CSSClass="viewSourceGrid" OnRowDataBound="PopulateDateCodes">
<Columns>
<asp:TemplateField InsertVisible="False" HeaderStyle-Width="70px">
<ItemTemplate>
<asp:Label CssClass="sourceHeader" runat="server" Text= '<%# "Source: " + (Container.DataItemIndex + 1).ToString() %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="nfdBroker" HeaderText="NFD/Broker" InsertVisible="False" ReadOnly="True" SortExpression="nfdBroker" />
<asp:BoundField DataField="locationDescription" HeaderText="Material Location" SortExpression="materialLocation" />
<asp:BoundField DataField="origPkg" HeaderText="Original Packaging?" SortExpression="origPkg" />
<asp:BoundField DataField="oemCC" HeaderText="OEM C of C? " InsertVisible="False" ReadOnly="True" SortExpression="oemCC" />
<asp:BoundField DataField="minBuyQty" HeaderText="Minimum Buy Qty" SortExpression="minBuyQty" />
<asp:BoundField DataField="deliveryInfo" HeaderText="Delivery" SortExpression="delUOM" />
<asp:TemplateField InsertVisible="False" HeaderText="Date Codes" >
<ItemTemplate>
<asp:GridView ID="DateCodeGrid" runat="server" InsertVisible="False" DataKeyNames="dateCode" CSSClass="viewSourceGrid" >
<Columns>
<asp:BoundField DataField="dateCode" SortExpression="dateCode">
<ItemStyle Width="20%" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and then here is the code behind:
public partial class Controls_ViewSource : System.Web.UI.UserControl
{
//Set the Source Line Item
public int SourceLineItem { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.SourceLineItem = SourceLineItem;
RequestDB db = new RequestDB();
DataSet sources = db.GetSource(int.Parse(Request.QueryString["requestNumber"]), SourceLineItem);
Source.DataSource = sources;
Source.DataBind();
}
protected void PopulateDateCodes(object sender, GridViewRowEventArgs e)
{
RequestDB db = new RequestDB();
int index = e.Row.RowIndex;
GridView gv = (GridView)Source.Rows[0].FindControl("DateCodeGrid");
//int sourceLineItem = int.Parse(Source.DataKeyNames[0].ToString());
//Response.Write(Source.DataKeyNames[0].ToString());
DataSet dateCodes = db.GetDateCodes(71);
gv.DataSource = dateCodes;
gv.DataBind();
}
}
You would need to find the nested grid view in the row that is being data bound:
GridViewRow row = e.Row;
You need to make sure you are only doing this for data rows, not header or footer rows:
if(row.RowType == DataControlRowType.DataRow)
{
// Find the nested grid view
GridView nested = (GridView)row.FindControl("DateCodeGrid");
// The rest of your code for binding the nested grid view follows here
}
Related
I am working with a gridview which I want to select a row and then put the row in a datatable to bind with a repeater control. I am having trouble finding the selected rows using the checkbox control that I had put in the gridview. I have searched the internet and have found some information on finding controls recursively. I can find a checkbox control however the results are always a "false" checkedbox. My question, Do I need to do something when the checkbox is checked in order for the gridview to know that there was a change? The checkbox is not bound to any data in my datatable is is only used for selection purposes.
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#191970" HeaderStyle-ForeColor="White" ShowFooter="false" RowStyle-Wrap="false"
AlternatingRowStyle-BackColor="#80993c" AlternatingRowStyle-ForeColor="White" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" AllowSorting="true" ShowHeaderWhenEmpty="true" EmptyDataText="No Notaries found with the specified criteria." CssClass="GridView1" OnSorting="GridView1_Sorting1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="notaryselect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="firstname" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="lastname" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="suffix" HeaderText="Suffix" />
<asp:BoundField DataField="city" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="state" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="zipcode" HeaderText="Zip Code" SortExpression="Zipcode" />
<asp:TemplateField>
<HeaderTemplate>Cell Phone</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hyperCellPhone" runat="server" ForeColor="Gold"
NavigateUrl='<%# Eval("cellphone", "tel:{0}") %>'
Text='<%# Eval("cellphone") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Email</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hyperEmail" runat="server"
NavigateUrl='<%# Eval("email", "mailto:{0}") %>'
Text='<%# Eval("email") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="county" HeaderText="County" SortExpression="County" />
<asp:BoundField DataField="lat" HeaderText="Latitude" />
<asp:BoundField DataField="long" HeaderText="Longitude" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Width="50%" />
</asp:GridView>
Control check = FindControlRecursive(GridView1.Rows[i], "notaryselect");
The above line is some code just to find the checkbox. I was experimenting and found that a checkbox is returned but no matter what they all come back false which is leading me to think that since they are set to unchecked or false at the start I need to do something but I am just not sure. Everything I find on the internet shows it should work. Let me know what your thoughts are.
Here is the code for the recursive function.
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control c in Root.Controls)
{
Control fc = FindControlRecursive(c, Id);
if (fc != null)
return fc;
}
return null;
}
I found that code on this site from a similar question and wanted to see if that worked.
You don't need any recursive function.
So, say this gv with a check box:
(it can be set to a value in the table, or not - does not matter).
So, this gv:
runat="server" CssClass="table" AutoGenerateColumns="false"
width="42%" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server"
Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="view"
CssClass="btn" OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
GridView1.DataSource = rstData;
GridView1.DataBind();
}
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And we now see/get this:
Ok, so for the click/view button, we have this code:
protected void cmdView_Click(object sender, EventArgs e)
{
Button btnView = (Button)sender;
GridViewRow gRow = (GridViewRow)btnView.NamingContainer;
Debug.Print("Row index click = " + gRow.RowIndex);
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("Database PK id = " + PK);
CheckBox ckActive = (CheckBox)gRow.FindControl("chkActive");
if (ckActive.Checked)
Debug.Print("check box is true");
else
Debug.Print("Check box is false");
}
output:
Row index click = 2
Database PK id = 7
Check box is false
So, above is a row click sample.
But, for all rows, then this:
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox ckBox = (CheckBox)gRow.FindControl("chkActive");
Debug.Print($"Row index = {gRow.RowIndex} Checkbox value = {ckBox.Checked.ToString()}");
}
output:
Row index = 0 Checkbox value = True
Row index = 1 Checkbox value = False
Row index = 2 Checkbox value = False
Row index = 3 Checkbox value = True
Row index = 4 Checkbox value = False
Row index = 5 Checkbox value = True
Row index = 6 Checkbox value = True
Row index = 7 Checkbox value = True
And of course, above could also display the database PK value, and quite nice is such values don't have to be exposed client side in the GV.
eg:
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID];
I am very new to development in asp.net.
What I am TRYING to do is upon edit of a gridrow, provide a drop down list for a particular column.
User story: User enters text into termSearch textbox; A list of items matching the search criteria is returned. The Activity Status column has only 2 valid values; active, inactive.
My problems are as follows:
DropDownList/Text not reflected in designer if it is within TemplateField. When outside of TemplateField, designer detects it.
During a cast, value is being returned as null.
During DataSource method, drop down list (ddlActivity) returning null.
GridView (Activity Status Template Field)
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField DataField="CODE" ReadOnly="True" HeaderText="Term Code" HtmlEncode="False" Visible="true">
<ItemStyle Width="24%" />
</asp:BoundField>
<asp:BoundField DataField="DISPLAYLABEL" HeaderText="Label" HtmlEncode="False" Visible="true">
<ItemStyle Width="24%" />
</asp:BoundField>
<asp:TemplateField HeaderText="Activity Status">
<ItemTemplate>
<asp:TextBox ID="lblActivity" runat="server" Text='<%#Bind("STATUS_FK") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlActivity" runat="server" SelectedValue='<%# Bind("STATUS_FK") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="STRINGATTRIBUTE" HeaderText="String Attribute" HtmlEncode="False" Visible="true">
<ItemStyle Width="24%" />
</asp:BoundField>
<asp:BoundField DataField="LONGLABEL" HeaderText="Long Label" HtmlEncode="False" Visible="true">
<ItemStyle Width="24%" />
</asp:BoundField>
</Columns>
Code Behind
protected void gvSearch_DataBound(object sender, GridViewRowEventArgs e)
{
string code = termSearch.Text;
ddlActivity.DataSource = termDAO.SearchByCode(code);
DropDownList ddlActivityStatus = (DropDownList)e.Row.FindControl("ddlActivity");
ddlActivityStatus.Items.Insert(0, new ListItem("--Select a Status--", "0"));
ddlActivityStatus.Items.Add(new ListItem("Active", "STATUS.A"));
ddlActivityStatus.Items.Add(new ListItem("Inactive", "STATUS.I"));
}
ddlActivity is in the EditItemTemplate. So you have to check for that.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlActivityStatus = (DropDownList)e.Row.FindControl("ddlActivity");
}
}
}
I am developing a Web App for managing Student exam entries but I am coming across an issue with my gridview.
The basic idea is that a user can go on and enter and update details on a students exam. Complications arise when certain subjects require different fields to be populated and this is where my issue is.
The exception is thrown when the Save Button method is run. I get a Null Object reference thrown when running the AddAudit and UpdateRecord methods. After some debugging from the looks of it the issue is the controls (ddlDate, txtAssesmentLevel etc) are not being declared from the FindCotrol method of the gridview meaning when the AddAudit and UpdateRecord methods are called they point to a null controller.
Be aware that this issue does not occur when the code is not "C2555" which leads me to suspect the issue is with dynamically adding columns and controls getting muddled up though i am not sure.
Any assistance would be great and feel free to ask for more information.
Below is my basic code:
Page Load Method
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
//Selected class passed through
selectedClass sc = (selectedClass)Session["selectedClass"] as selectedClass;
//Get Class Code
lblAosCode.Text = sc.getAOSCode();
//If class is English
if(lblAosCode.Text == "C2555"){
TemplateField speakingListening = new TemplateField();
speakingListening.HeaderText = "Speaking and Listening";
dgvSelectedClasses.Columns.Insert(7, speakingListening);
}
//Populate Gridview
DataTable dsSelectedClasses = AccessData.getSelectedClasses(sc.getAOSCode(), sc.getAOSPeriod(), sc.getDescription());
dgvSelectedClasses.DataSource = dsSelectedClasses;
dgvSelectedClasses.DataBind();
//Check if txtAssesmentLevel is populated
for (int index = 0; index < dgvSelectedClasses.Rows.Count; index++)
{
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[index].FindControl("txtAssessmentLevel");
if (dgvBefore.Rows[index].Cells[4].Text != " ")
{
txtAssessmentLevel.ReadOnly = true;
}
}
}
}
Save Method (Exception Thrown)
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvSelectedClasses.Rows.Count; i++)
{
DropDownList ddlL1L2 = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlL1L2");
DropDownList ddlExamDate = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlExamDate");
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[i].FindControl("txtAssessmentLevel");
DropDownList ddlSpeakingListening = null;
if (lblAosCode.Text.Contains("C2555"))
{
ddlSpeakingListening = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlSpeakingListening");
}
if (IsPostBack)
{
if (lblAosCode.Text.Contains("C2555"))
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[15].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Speaking and Listening", ddlSpeakingListening.SelectedValue, dgvBefore.Rows[i].Cells[7].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text, ddlSpeakingListening.SelectedValue);
}
else
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[13].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text);
}
}
}
Response.Redirect("~/contact");
}
On Row Data Bound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (lblAosCode.Text.Contains("C2555"))
{
DropDownList ddlSpeakingListening = new DropDownList();
ddlSpeakingListening.ID = "ddlSpeakingListening";
ddlSpeakingListening.Items.Add("L1");
ddlSpeakingListening.Items.Add("L2");
ddlSpeakingListening.Items.Add("Entry");
ddlSpeakingListening.Items.Add("NS");
e.Row.Cells[7].Controls.Add(ddlSpeakingListening);
}
}
}
ASP.NET
<asp:GridView ID="dgvSelectedClasses" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:TemplateField HeaderText="Assessment Level">
<ItemTemplate>
<asp:TextBox ID="txtAssessmentLevel" Text ='<%#Bind("AssessmetLevel") %>' runat="server" Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="Achievelevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Last Update" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:TemplateField HeaderText="Exam request L1 or L2" >
<ItemTemplate>
<asp:DropDownList ID="ddlL1L2" runat="server" >
<asp:ListItem>Not Set</asp:ListItem>
<asp:ListItem>L1</asp:ListItem>
<asp:ListItem>L2</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam date">
<ItemTemplate>
<asp:DropDownList ID="ddlExamDate" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="dgvBefore" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:BoundField DataField="AssessmetLevel" HeaderText="Assessment Level" NullDisplayText=" "/>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="AchieveLevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Date Spreadsheet Sent" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="ExamrequestL1orL2" HeaderText="Exam request L1 or L2" />
<asp:BoundField DataField="Examdate" HeaderText="Exam date" />
<asp:BoundField DataField="Reviewed" HeaderText="Reviewed" />
</Columns>
</asp:GridView>
P.S. This is my first question hopefully it makes sense and I am open to pointers :)
Edit: The page load method does include code to populate dgvBefore as well as a few authentications thing i just forgot to include it.
I think you need to add the drop down list column on every postback. Refer this link : https://www.codeproject.com/Tips/682689/Add-populated-dropdownlist-to-GridView-dynamically
I have gridview control it contains 6 columns when i click 6th column row of gridview i need to selecte that contains columns row text into a string. how can i take here i am taking commandargument is a string and how can i take another column names text
my code:
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="" ItemStyle-ForeColor="White" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="SName" HeaderText="SName" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Size" HeaderText="Size(MB)" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
CommandName="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No." Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string ID1;
if (e.CommandName == "Download")
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
Label Itemid = (Label)GridView1.Rows[rowIndex].FindControl("lblID");
ID1 = (Itemid).Text;
Session["ID"] = ID1;
string filename = e.CommandArgument.ToString();
//here how can i hold another column text
}
}
I have a easiest way to do this same thing...
<asp:Label ID="lblName" runat="server" Text='<%#Eval("ID").ToString() +", "+ Eval("OtherCoulmn").ToString() %>'></asp:Label>
--- hope it helps
Also the best way is to do something like this
((MyObject)Container.DataItem).MyProperty where MyObject is the Model which you bind with grid and property which you wan to use in rowcommand its clean .
Simply follow the bellow code sample:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
Label lblId = gvCipamMember.Rows[gvr.RowIndex].FindControl("lblPersonId") as Label;
cmd = new SqlCommand("SELECT Id,Res_Person,Email_ID,Mobile_NO,Cipam_Flag FROM Responsibilty_Master WHERE Id=#Id", con.MyConnection);
cmd.Parameters.AddWithValue("#Id", Convert.ToInt32(lblId.Text.ToString()));
dt = new DataTable();
con.MyConnection.Open();
dt.Load(cmd.ExecuteReader());
if (dt.Rows.Count > 0)
{
txtPersonName.Text = dt.Rows[0]["Res_Person"].ToString();
txtEmail.Text = dt.Rows[0]["Email_ID"].ToString();
txtMobileNo.Text = dt.Rows[0]["Mobile_NO"].ToString();
if(Convert.ToBoolean(dt.Rows[0]["Cipam_Flag"].ToString())==true)
{
chkbCipamFlag.Checked = true;
}
}
}
I have been trying this out for a while now and can't seem to figure it out. I can extract the controls in the gridview fine, but I need to get the values of the databound cells in the GridView, and cant seem to find out how. Here is my code:
Webpage:
<asp:GridView ID="ReceiverPanel" runat="server" AutoGenerateColumns="False" DataSourceID="ODSPopulatePOItemList">
<Columns>
<asp:BoundField DataField="PurchaseOrderID" HeaderText="PurchaseOrderID" SortExpression="PurchaseOrderID" Visible="False" />
<asp:BoundField DataField="StockItemID" HeaderText="StockItemID" SortExpression="StockItemID" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="QuantityOnOrder" HeaderText="QuantityOnOrder" SortExpression="QuantityOnOrder" />
<asp:BoundField DataField="QuantityOutstanding" HeaderText="Outstanding" SortExpression="QuantityOutstanding" />
<asp:TemplateField HeaderText="Receive">
<ItemTemplate>
<asp:TextBox runat="server" ID="Received" Text='<%# Eval("Received") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Return">
<ItemTemplate>
<asp:TextBox runat="server" ID="Returned" Text='<%# Eval("ReturnedQuantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason">
<ItemTemplate>
<asp:TextBox runat="server" ID="Reason" Text='<%# Eval("Reason") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void ReceiveButton_Click(object sender, EventArgs e)
{
// Gather data from gridview
foreach (GridViewRow row in ReceiverPanel.Rows)
{
// Find controls in the Gridview
//var purchaseOrderIdCtrl = row.FindControl("PurchaseOrderID") as HiddenField;
//var stockItemCtrl = row.FindControl("")
var receivedCtrl = row.FindControl("Received") as TextBox;
var returnedCtrl = row.FindControl("Returned") as TextBox;
var reasonCtrl = row.FindControl("Reason") as TextBox;
//SELECT DATABOUND CONTROL var stockItemNo = row.SelectedRow.Cells[2].Text ;
//int stockItemNum = int.Parse(stockItemNo);
int received = int.Parse(receivedCtrl.Text);
int returned = int.Parse(returnedCtrl.Text);
string reason = reasonCtrl.Text;
Update_StockItem(stockItemNum, received);
}
Is there a simple way to grab the values from the GridView? Any help would be greatly appreciated.
try like this
You Need Specify Index of Bound Field Like PurchaseOrderID is first BoundField so its index is 0
foreach (GridViewRow row in ReceiverPanel.Rows)
{
string PurchaseOrderID =row.Cells[0].Text
}