Cell Text Always &nbsp: - c#

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}

You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>

I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Related

GridView with SortExpression in column - I can't read the HeaderRow to make an Excel file with EPPlus - C Sharp C#

I' ve got an issue with my program.
When i do this:
GridView gvw = this.ProduttoriList1.FindControl("GridViewList") as GridView;
SqlDataSource dataSource = this.ProduttoriList1.FindControl(gvw.DataSourceID) as SqlDataSource;
FileInfo tempXlsFile = new FileInfo(HttpRuntime.CodegenDir + "\\" + Guid.NewGuid() + ".xlsx");
string filename = string.Format("Produttori_{0}.xlsx", Guid.NewGuid().ToString());
try
{
gvw.AllowPaging = false;
gvw.DataSourceID = string.Empty;
gvw.DataSource = dataSource;
gvw.DataBind();
//...some export commands with EPPlus...
}
catch (Exception exception)
{
throw exception;
}
finally
{
System.IO.File.Delete(tempXlsFile.ToString());
}
and i'm going to read the HeaderRow, i can't read the column that has a SortExpression (return a "" value).
<asp:Panel ID="Panel2" runat="server" Style="padding-top: 10px">
<asp:GridView ID="GridViewList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceList"
Width="100%" AllowPaging="True" AllowSorting="True" SkinID="GridViewDefault"
DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderStyle-Width="30px" HeaderText="N°">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>.
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DescrLongITA" HeaderText="Produttore" SortExpression="DescrLongITA" />
<asp:TemplateField HeaderText="Modifica">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonEdit" runat="server" ImageUrl="~/Images/Icons/modifica.gif"
CommandArgument='<%# Eval("ID") %>' OnClick="ImageButtonEdit_Click" />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Elimina">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Icons/elimina.gif"
OnClientClick="return confirm("Continuare la cancellazione?")" CommandArgument='<%# Eval("ID") %>'
OnClick="ImageButtonDelete_Click" />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div style="color: #FF0000; padding: 30px">
<asp:Label ID="LabelEmpty1" runat="server" Text="Nessun dato trovato"></asp:Label>
</div>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
In this case, i can't read the BoundField with HeaderText = "Produttore".
How can i do?
I found the solution, i hope to help you.
When I perform the preliminary steps of the export procedure and do this..
string[] columns = new string[gv.HeaderRow.Cells.Count];
for (int i = 0; i < columns.Length; i++)
{
columns[i] = gv.HeaderRow.Cells[i].Text;
}
Export(tmpFile, gv, columns);
i've replaced this one
columns[i] = gv.HeaderRow.Cells[i].Text;
with this one
var headertext = gv.Columns[i].HeaderText;
columns[i] = new DataColumn(headertext).ToString();

Binding Shopping Cart Check box Session onto another Gridview

I am new to asp.net and I am trying to make a shopping cart. I have a shop set up that has a list of school supplies and a check box next to each one with a "Add to Cart" button on the bottom. I want to store only the checked items into a session and call it to another gridview on my Shopping Cart page. For some reason my gridview on my Shopping cart page is not appearing.
Shop.aspx
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Price" DataFormatString="{0:c2}" HeaderText="Price" SortExpression="Price" />
<asp:TemplateField HeaderText="Add To Cart">
<ItemTemplate>
<asp:CheckBox ID="cbAdd" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table] ORDER BY [Id], [Name], [Price]"></asp:SqlDataSource>
</div>
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add To Cart" OnClick="btnAdd_Click" />
Shop.aspx.cs
protected void Page_Load(object sender, EventArgs e)//bind list to gridview
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();//create new datatable
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("ID"), new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in gvProducts.Rows)//for each row in the gridview
{
CheckBox ckRow = (CheckBox)row.FindControl("ckAdd");
if (ckRow !=null && ckRow.Checked)
{
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
Session["ShoppingCart"] = dt;//store datatable as session called ShoppingCart
}
Response.Redirect("~/ShoppingCart.aspx");
}
ShoppingCart.aspx
<h1>Shopping Cart</h1>
<asp:GridView ID="gvProductsList" runat="server" AutoGenerateColumns="true" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Textbox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Total">
<ItemTemplate>
<asp:Label ID="lblProductTotal" runat="server" Text='<%# Convert.ToInt32(Eval("Quantity"))*Convert.ToInt32(Eval("Price"))%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
</FooterTemplate>
</asp:TemplateField>
ShoppingCart.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = (DataTable)Session["ShoppingCart"];
gvProductsList.DataSource = dt;
gvProductsList.DataBind();
}
}
Try this:-
List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().
Where(x => (x.FindControl("cbAdd") as CheckBox)
.Checked == true).ToList();
I used below custom data to bind the grid gvProducts
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Sharique";
dr[2] = "120";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "Ansari";
dr[2] = "100";
dt.Rows.Add(dr);
gvProducts.DataSource = dt;
gvProducts.DataBind();
}
}
use this to bind you grid gvProductsList
List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().Where(x => (x.FindControl("cbAdd") as CheckBox).Checked == true).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("Count");
dt.Columns.Add("Quantity");
foreach (GridViewRow gvr in gridcheckedrows)
{
DataRow dr = dt.NewRow();
dr["Id"] = gvr.Cells[0].Text;
dr["Name"] = gvr.Cells[1].Text;
dr["Price"] = gvr.Cells[2].Text;
dr["Count"] = "1";
dr["Quantity"] = "2";
dt.Rows.Add(dr);
}
gvProductsList.DataSource = dt;
gvProductsList.DataBind();
and for grid gvProductsList use below html
<asp:GridView ID="gvProductsList" runat="server">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Total">
<ItemTemplate>
<asp:Label ID="lblProductTotal" runat="server" Text='<%# ((Convert.ToInt32(Eval("Quantity")))*(Convert.ToInt32(Eval("Price"))))%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Hope this will help you.

finding label in itemTemplate and bind data from code behind

I wanted to display value in a label (label inside itemTemplate)
i have tried this approach
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
string LabelText = ((Label)row.FindControl("labelSelf")).Text;
LabelText = s;
Response.Write(LabelText+"test");
}
}
but nothing is shown in the label inside the gridview. IT should display the value of s.
Next approach was
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
Label labelSelfCollect = GridView1.FindControl("labelSelf") as Label;
labelSelfCollect.Text = "Self Collect at "+ s;
I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
and the last approach that i have used is
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label labelcollect = row.FindControl("labelSelf") as Label;
labelcollect.Text = "self collect at "+ s;
}
}
}
using this method also it shows nothing.How should i assign the s value into this labelSelf(label inside itemTemplate)?
my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="772px" style="margin-left: 120px; text-align: left" Height="100px" DataKeyNames ="progressID" OnRowDataBound="GridView1_OnRowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" CssClass="rounded_corners" HeaderStyle-Height="40px">
<AlternatingRowStyle CssClass="rounded_corners tr tr" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="60" DataField="dateupdate" HeaderText="Date Update" DataFormatString="{0:dd/MM/yyyy}" >
<ControlStyle BorderWidth="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Progress">
<ItemTemplate >
<%# Eval("message") %>
<br />
<asp:label ID="labelRemark" runat="server" style="Font-Size:11.5px;" text='<%# Eval("remark") %>'></asp:label><br />
<asp:Label ID="labelSelf" runat="server" style="Font-Size:11.5px;" ></asp:Label><br />
<div id="div<%# Eval("progressID") %>" >
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="progressID" style="text-align:center; font-size:small;" CellPadding="4" OnRowCommand="GridView2_RowCommand" GridLines="None" CssClass="rounded_corners" Width="500px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="tackingNo" HeaderText="Courier Tracking No" ItemStyle-Font-Size="Small" ItemStyle-Width="150px" >
</asp:BoundField>
<asp:BoundField DataField="courierDate" HeaderText="Courier Date">
</asp:BoundField>
<asp:TemplateField HeaderText="Provider">
<ItemTemplate>
<asp:HyperLink Text='<%#Eval("providernm")%>' Target="_blank" runat="server" DataNavigateUrlFields="companyurl" NavigateUrl='<%#Eval("companyurl")%>' ></asp:HyperLink>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tracking" >
<ItemTemplate>
<br />
<asp:HyperLink Text="Track Here" Target="_blank" runat="server" DataNavigateUrlFields="trackingurl" NavigateUrl='<%#Eval("trackingurl")%>' ></asp:HyperLink>
<br />
<asp:Label ID="Label4" runat="server" Text="* check after 24 hours" Font-Italic="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonDELETE" runat="server" CommandName="Delete" Text="Delete" OnClientClick= "return confirm('Confirm Delete progress?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thank you.
Use GridView1_OnRowDataBound instead of foreach (GridViewRow row in GridView1.Rows). Apart from that your first approach is correct. You're simply not assigning the Text property there but reading from it.
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label labelSelf = (Label)e.Row.FindControl("labelSelf");
labelSelf.Text = address.getSelfCollectAddress(orderNoTracking); // maybe you need to retrieve the orderNoTracking from another control in this row or from it's datasource
}
}

How to Access elements of a checked/selected row elements of gridview

I am working in windows 8.2 and was working to insert a selected row to my data base and i have web form which have a grideview with checkboxes to select/deselect and an event to insert.
the code of the web form is as
<asp:Panel runat="server" ID="pnlStudData">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:checkbox runat="server" ID="chKCheckAll" onclick="javascript:SelectAllCheckboxes(this)"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkCheck" onclick="javascript:CheckedCheckboxes(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Id">
<ItemTemplate>
<asp:Label ID="lblStudName" runat="server" Text='<%#Eval("Stud_Id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Name">
<ItemTemplate>
<asp:Label ID="lblMiddleName" runat="server" Text='<%#Eval("MiddleName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cumpase">
<ItemTemplate>
<asp:Label ID="lblCumpase" runat="server" Text='<%#Eval("Cumpase")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lblCollege" runat="server" Text='<%#Eval("College")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%#Eval("Dept")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Block">
<ItemTemplate>
<asp:Label ID="lblBlock" runat="server" Text='<%#Eval("Block")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dorm Number">
<ItemTemplate>
<asp:Label ID="lblDormNo" runat="server" Text='<%#Eval("Dorm")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<br />
<asp:Button ID="Save" runat="server" Text="Save" Width="169px" Height="46px" OnClick="Save_Click" />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
</asp:Panel>
and the java script to select/deselect a check-box as
<script language="javascript" type="text/javascript">
function SelectAllCheckboxes(chk)
{
var totalRows = $("#<%=GridView1.ClientID%> tr").length;
var selected = 0;
$('#<%=GridView1.ClientID%>').find("input:checkbox").each(function () {
if (this != chk) {
this.checked = chk.checked;
selected += 1;
}
});
}
function CheckedCheckboxes(chk)
{
if(chk.checked)
{
var totalRows = $('#<%=GridView1.ClientID %> :checkboxes').length;
var checked = $('#<%=GridView1.ClientID %> :checkbox:checked').length;
if(checked==(totalRows-1))
{
$('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
this.checked = true;
});
}
else
{
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
else {
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
</script>
and the button save click event which sends this selected row cells to a database class insert method as
foreach(GridViewRow gd in GridView1.Rows)
{
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// gd.Cells[0].Visible = false;
string stId = gd.Cells[1].Text.ToString();
string fName = gd.Cells[2].Text.ToString();
string mName = gd.Cells[3].Text.ToString();
string lName = gd.Cells[4].Text.ToString();
string cumpas = gd.Cells[5].Text.ToString();
string college = gd.Cells[6].Text.ToString();
string dept = gd.Cells[7].Text.ToString();
int bl = Convert.ToInt32(gd.Cells[8].Text);
int dormNo = Convert.ToInt32(gd.Cells[9].Text);
DbCon db = new DbCon();
if (db.RegisterStud(stId, fName, mName, lName, cumpas, college, dept, bl, dormNo) == 1)
{
Label1.Text = "You Have Inserted";
}
else
{
Label1.Text = "Errror";
}
}
else { Label1.Text = "Please select a row"; }
}
but i can't find each cells value and not assigned to those string variables.
When using <asp:TemplateField>, the data is not inside Cell but is contained in the Control present inside the Cell.
row.Cells[].Text works only when using <asp:BoundField> for GridView Columns.
So, There are two steps to read the value when using <asp:TemplateField>:
Access the Control inside Cell
Access the Value from Control in step 1
I see you did the above steps to read the Checkbox value from first Column already. Follow the same for all other Columns.
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// Step 1: Access the Control inside Cell
Label lblName = (Label)gd.Cells[1].FindControl("lblStudName");
// Step 2: Access the Value from Control in step 1
string Name = lblName.Text;
// Combine Step 1 & Step 2: Access Values in one line
string Name = ((Label)gd.Cells[1].FindControl("lblStudName")).Text;
string firstName = ((Label)gd.Cells[2].FindControl("lblFirstName")).Text;
// ....same way for all Columns which use a <asp:TemplateField>
}

Trying to Add Insert Row to Footer in GridView ASP.net

I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}

Categories