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
}
Related
I have a GridView with textBoxes inside ItemTemplates. I can retrieve the data from the column that was binded to the Gridview on page load, however, I do not see any of the manually entered text when reading the cell values.
The HTML:
<asp:GridView ID="tblRentDue" runat="server" ClientIDMode="Static">
<Columns>
<asp:BoundField DataField="Application_ID" HeaderText="Application ID" HeaderStyle-Wrap="false" />
<asp:BoundField DataField="Month" HeaderText="Month" HeaderStyle-Wrap="false" />
<asp:TemplateField HeaderText="Orignal Amount Due">
<ItemTemplate>
<asp:TextBox ID="txtOrignalAmountDue" runat="server" TextMode="Number" Text='<%# Eval("Original_Amount_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fees Due">
<ItemTemplate>
<asp:TextBox ID="txtFeesDue" runat="server" TextMode="Number" Text='<%# Eval("Fees_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount Paid">
<ItemTemplate>
<asp:TextBox ID="txtAmountPaid" runat="server" TextMode="Number" Text='<%# Eval("Amount_Paid") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Still Due">
<ItemTemplate>
<asp:TextBox ID="txtTotalStillDue" runat="server" TextMode="Number" Text='<%# Eval("Total_Still_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind:
public DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
dt.Columns.Add("Month");
dt.Columns.Add("Original_Amount_Due");
dt.Columns.Add("Fees_Due");
dt.Columns.Add("Amount_Paid");
dt.Columns.Add("Total_Still_Due");
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
dr["Month"] = (row.Cells[0].Text); //These values are showing up and was loaded from the database.
dr["Original_Amount_Due"] = (row.Cells[1].Text); //Nothing showing from user input
dr["Fees_Due"] = (row.Cells[2].Text); //Nothing showing from user input
dr["Amount_Paid"] = (row.Cells[3].Text); //Nothing showing from user input
dr["Total_Still_Due"] = (row.Cells[4].Text); //Nothing showing from user input
dt.Rows.Add(dr);
}
return dt;
}
The solution I found - within the foreach loop for each textbox:
TextBox orignalAmount = (TextBox)row.Cells[1].FindControl("txtOrignalAmountDue");
dr["Original_Amount_Due"] = orignalAmount.Text;
There may be a less clunky way of doing this but it does work.
I have a GridView on which I am binding 2 textbox and a update button. grid view is dynamic so Row numbers can vary depending upon the size of dataset. Now what I want is when I change values in this textbox and click on update then data for that row in database should get updated. The textbox values in database should get updated.
This is my code:
<asp:GridView ID="dgAbstractSummary" runat="server" AutoGenerateColumns="False" OnRowDataBound="dgAbstractSummary_RowDataBound" OnRowCreated="dgAbstractSummary_RowCreated"
Visible="true">
<Columns>
<asp:BoundField HeaderText="ID" DataField="id" HtmlEncode="false"></asp:BoundField>
<asp:BoundField HeaderText="Abstract Title" DataField="title" HtmlEncode="false"></asp:BoundField>
<asp:TemplateField HeaderText="Significance Score">
<ItemTemplate>
<asp:TextBox ID="txtSignificanceScore" AutoPostBack="true" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"significanceScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Innovation Score">
<ItemTemplate>
<asp:TextBox ID="txtInnovationScore" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"innovationScore")%>'></asp:TextBox>
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button AutoPostBack="true" CssClass="btn btn-primary btn-embossed" ID="btnUpdate" runat="server"
Text="Update"
OnClick="btnUpdate_Click" CommandArgument='<%#Eval("Id") %>' />
<div class="voffset3"></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="panel-default"></HeaderStyle>
<RowStyle CssClass=""></RowStyle>
</asp:GridView>
C#
dgAbstractSummary.DataSource = dsResult; // dataset contains values which I am binding to grid columns
dgAbstractSummary.DataBind();
protected void btnUpdate_Click(object sender, EventArgs e)
{
Button myUpdateButton = (Button)sender;
}
Here Id (first column) is the unique key for each row.
Use find control function to find the two text boxes on the grid view row using your buttons sender event.
Something like this.
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
TextBox details = gvr.FindControl("detailsText") as TextBox;
//do something with details
TextBox cusID = gvr.FindControl("TextBox2") as TextBox;
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 a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}
I have a gridview and in the gridview i got a item template as follows
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
Now on every row in the gridview i need to bind this to the data, but i am having trouble finding it and binding it to the data.
The gridview has 4 templatefields with 1 itemtemplate within each template field like this
<asp:TemplateField HeaderText="Product Name" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Products" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:FileUpload runat="server" ID="image" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:CheckBox Text="Active" runat="server" ID="active" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
And I am trying to bind the drop down as follows
protected void Grid_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
// Bind Products
Product productManager = new Product();
TList<Product> dsProduct= productManager.GetAll();
DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList;
if (dsProduct != null)
{
DataView dvProduct = new DataView(dsProduct.ToDataSet(true).Tables[0]);
dvProduct.Sort = "name asc";
ddlProducts.DataSource = dvBrand;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
ListItem li = new ListItem("No Product Selected", "0");
ddlProducts.Items.Insert(0, li);
}
}
I am getting a out of index in the line DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList; I am learning this process so i would appreciate some help in terms of what i am doing wrong and what i need to change. I would really appreciate any help.
You must use FindControl to find controls in a TemplateField. You also need to exclude the header-row:
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
DropDownList ddlProducts = (DropDownList)e.Row.FindControl("ddlProductNames");
ddlProducts.DataSource = someDataSource;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
}
}
You also don't need to call productManager.GetAll() for every row in the Grid. You only need to get the products for the current Row. If the source is the same for every row, you should create it before you bind the GridView as member-variable. Then you don't need to retrieve the same data for each row.