How to fill up a GridView with foreach loop - c#

I have this GridView markup:
<asp:GridView ID="GridView1" runat="server" Width ="300px">
<Columns>
<asp:BoundField AccessibleHeaderText="TEXT" HeaderText="TEXT" />
</Columns>
</asp:GridView>
I want to fill up Gridview with some strings through foreach loop:
foreach (GridViewRow row in GridView1.Rows)
{
string f = "this is looping";
row.Cells[0].Text += f;
}
The problem is GridView1 doesn`t display anything...

Well, you can say have a gv like this:
<asp:GridView ID="GridView1" runat="server" CssClass="table" Width="20%">
</asp:GridView>
And then code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
List<string> MyList = new List<string> { "One", "Two", "Three" };
GridView1.DataSource = MyList;
GridView1.DataBind();
}
And we get this:
Or, we can add a listitem (often used for a drop down list, or say listbox).
Thus:
<asp:GridView ID="GridView1" runat="server" CssClass="table"
Width="20%" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="My header"
DataField="Text"/>
</Columns>
</asp:GridView>
(note how we turned off autogen colums)
code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
List<ListItem> MyList = new List<ListItem>();
MyList.Add(new ListItem("One"));
MyList.Add(new ListItem("Two"));
MyList.Add(new ListItem("Three"));
GridView1.DataSource = MyList;
GridView1.DataBind();
}
And we now have this:
So, you can use a simple string list, or even a list item. You loop adding to the object, and THEN feed to the gv.
so, you can loop and build up something, but that thing is THEN bound to the gv.

You can't use foreach loop becouse your GridView doesn't have data source.
Set ObservableCollection as Source, and Add data to collection.

Related

How to fetch values from cells inside Grid View

I have used grid view in my ASP.NET application.
<asp:GridView ID="grdView" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Jurisdiction">
<ItemTemplate>
<asp:Label ID="lblJurisdiction" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
in cs file
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
Note that the above grid will be populated by data. Now I need to get data from already populated gridview. The above code is not working. Also I need to retrieve from labels, textboxes, checkboxes values inside grid. Please help !!!
You can use FindControl method to retrieve the control's data:-
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
CheckBox chkbox = row.FindControl("chkbox") as CheckBox;
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
..and so on
//Finally retrieve the data like your normal control
string labelText = lblJurisdiction.Text;
}
}
Use GridViewRow.FindControl method.
foreach (GridViewRow row in grdView.Rows)
{
// return you the check-box control from current row
var chkbox = row.FindControl("chkbox");
}
Check whether the row type is DataControlRowType.DataRow.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
}
To get the TextBox, CheckBox value from the grid use this,
string TextBoxvalue = ((TextBox)GridViewID.Rows[i].FindControl("TextBoxName")).Text;
string CheckBoxvalue = ((CheckBox)GridViewID.Rows[i].FindControl("CheckBoxName")).Text;
In your code .cs file, you are missing to check only for datarow. As it will check all 3 places:-
1. Header
2. Body
3. Footer
Might any one place, any exception can occur.
Please add one more if condtion just after the for loop, as below.
if (row.RowType == DataControlRowType.DataRow)
{
Hope this post will help's you :).
Use
cells[i].EditedFormatedValue

How to delete a row without using OnRowDeleted/OnRowDeleting in gridview

Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you

Variables lost on postback in asp.net

I have a gridview with some data and I want to add a checkbox column which can choose multiple rows. By clicking on it I want to save an primary key of row and change css class of row.
Using this article(step 2) I created itemtemplate,added there a checkbox(specifying ID as TransactionSelector), and add a checkedChange() to it. There I only change a css class of row and add a row index to arraylist. But when I click button with event which show this list, it has no items.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="TransactionSelector" runat="server"
oncheckedchanged="TransactionSelector_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="iTransactionsId" HeaderText="iTransactionsId"
SortExpression="iTransactionsId" />
<asp:BoundField DataField="mAmount" HeaderText="mAmount"
SortExpression="mAmount" />
<asp:BoundField DataField="vchTransactionType" HeaderText="vchTransactionType"
SortExpression="vchTransactionType" />
<asp:BoundField DataField="dtDate" HeaderText="dtDate"
SortExpression="dtDate" />
<asp:BoundField DataField="cStatus" HeaderText="cStatus"
SortExpression="cStatus" />
<asp:BoundField DataField="test123" HeaderText="test123"
SortExpression="test123" />
</Columns>
<RowStyle CssClass="unselectedRow" />
</asp:GridView>
</asp:Panel>
<asp:Panel ID="InfoPanel" runat="server" CssClass="infoPanel">
<asp:Button ID="ShowSelected" runat="server" Text="Button"
onclick="ShowSelected_Click" />
<asp:Label ID="InfoLabel" runat="server"></asp:Label>
</asp:Panel>
C Sharp code:
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList indices = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void TransactionSelector_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
// row.CssClass = (cb.Checked) ? "selectedRow" : "unselectedRow";
if (cb.Checked)
{
row.CssClass = "selectedRow";
indices.Add(row.RowIndex);
}
else
{
row.CssClass = "unselectedRow";
indices.Remove(row.RowIndex);
}
}
protected void ShowSelected_Click(object sender, EventArgs e)
{
InfoLabel.Text = "";
foreach (int i in indices)
{
InfoLabel.Text += i.ToString() + "<br>";
}
}
}
}
You have to persist variable in postback using ViewState. Also its better if you use List<T> generic implementation rather than ArrayList
ViewState["Indices"] = indices;
And to recover it back
indices = ViewState["Indices"] as ArrayList;
As Habib said, you could use ViewState. You could also use ControlState instead, as shown here. If your code is in a custom control or user control, you may also need to override OnInit to
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
Please feel free to respond with feedback. I'm new at posting answers.

GridCheckBoxColumn with an string value

I need that an GridCheckBoxColumn contains a string value from my table SQL for this row (id).
OBS: I work with ASP.NET framework 4, Telerik, C# and SQL Server.
The scenario:
in table SQL, i have multiple rows (columns sub_folder_path(varchar),groupM(varchar),groupR(varchar) are most important!).
in my webapp (asp.net), a call this table and create an RadGrid(Telerik) with informations from SQL (the same column name).
I need create an column in webapp (asp.net) 2 GridCheckBox (GroupR and GroupM), and for each row, I can choose just GroupR or GroupM.
When I select an option for GridCheckBox (GroupR and GroupM), I need move to .CS Group name selected (varchar) for each row.
My code asp.net
<telerik:GridCheckBoxColumn DataField="securityGroupR" HeaderText="Access to Modify"
SortExpression="securityGroupR" UniqueName="securityGroupR" DataType="System.String">
</telerik:GridCheckBoxColumn>
<telerik:GridCheckBoxColumn DataField="securityGroupM" HeaderText="Access to Modify"
SortExpression="securityGroupM" UniqueName="securityGroupM" DataType="System.String">
</telerik:GridCheckBoxColumn>
Error: String was not recognized as a valid Boolean.
How can I create GridCheckBox that passes for my .CS group name for each selected row?
Tks!
Please try with below code snippet.
.ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Get selected Checbox" />
.ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("flag", typeof(string));
dt.Rows.Add(1, "true");
dt.Rows.Add(2, "true");
dt.Rows.Add(3, "false");
RadGrid1.DataSource = dt;
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
DataRowView dr = item.DataItem as DataRowView; // Convert DataItem into Your Assigned Object
(item.FindControl("CheckBox1") as CheckBox).Checked = GetBoolValueFromString(Convert.ToString(dr["flag"]));
}
}
protected bool GetBoolValueFromString(string strFlag)
{
bool flag = false;
bool.TryParse(strFlag, out flag);
return flag;
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
if ((item.FindControl("CheckBox1") as CheckBox).Checked)
{
string strID = item["ID"].Text; // Get selected Checkbox's ID Field Value
}
}
}

Selecting row of DataGridView?

How do i have the whole row of a data grid view. I have no idea where to start. I have tried this, but has NO idea where to PUT it. :
dataGrid.Rows[index].Selected = true;
I am just looking for a peice of code that will help me! Thanks
It seems you want to do something like this:
protected void Page_Load(object sender, EventArgs e)
{
this.FillGrid();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.GridView1.SelectedIndex = e.NewSelectedIndex;
this.FillGrid();
}
private void FillGrid()
{
this.GridView1.DataSource = new[] { "Hello", "World" };
this.GridView1.DataBind();
}
And in the aspx file:
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanging="GridView1_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
</asp:GridView>
Which produces this output:

Categories

Resources