How to bind gridview with data by using loop? - c#

I have written code like below lines of code
protected void grdView_DataBinding(object sender, EventArgs e)
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, LicenseType);
foreach (GridViewRow row in grdView.Rows)
{
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
TextBox txtDateIssued = row.FindControl("txtEffectiveDate") as TextBox;
TextBox txtDateExpiration = row.FindControl("txtExpirationDate") as TextBox;
TextBox txtLicenseNumber = row.FindControl("txtLicenseNumber") as TextBox;
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
txtLicenseNumber.Text = lds.Tables[0].Rows[i]["LicenceNumber"].ToString();
}
}
}
I want to bind grid view without using datasource property of gridview. The above code is not working...
Let's Suppose lds contains data like
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Similarily Grid will also contain the data
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Here is grid view's design
<asp:GridView ID="grdView" AutoGenerateColumns="false" OnDataBinding="grdView_DataBinding" BorderWidth="0" runat="server" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" style="padding:12px 5px;" runat="server" />
<br />
<asp:RequiredFieldValidator ID="ValReqLN" Display="Dynamic" runat="server"
ErrorMessage="License Number cannot be Blank." ControlToValidate="txtEffectiveDate"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:TextBox ID="txtEffectiveDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help!!!

Why would you not use datasource property ? you said: "i want to bind gridview programically because I have to give many conditions inside gridview's rows according to business logic in order to display data in the gridview.
Here is how you can do that:
Code behind:
protected void grdView_DataBinding(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["txtLicenseNumber"].ToString().ToLower() == "abc")
{
//Apply business logic here on each row, hide/show etc
e.Row.CssClass = "highlighted";
}
}
}
Read more here on:
Dynamically change GridView Cell value using RowDataBound event in ASP.Net using C# and VB.Net
Selectively apply css to a row in a gridview

Related

How to multiselect values in listbox into template filed asp. net

I try to multiselect values in listbox into template field, when it is in edit mode. Is there a way to do it?
I tried something like this. I add HiddenField to bind there a values and then w JS code I want to select selected values (I can do it but I dont have a class in HiddenField so it isn't a good solution).
Also I don't know is there a chance to do it by server side becasue it didn't recognize Id's of mine Listbox
<asp:TemplateField HeaderText="Conditions" ItemStyle-Width="100px">
<EditItemTemplate>
<asp:HiddenField runat="server" ID="hdn_dd_conditions" class="bottom" Value='<%# Bind("conditions") %>' />
<asp:ListBox ID="dd_conditions" runat="server" CssClass="conditions" SelectionMode="Multiple" multiple="multiple">
<asp:ListItem Value="Value1" Text="Text2"></asp:ListItem>
<asp:ListItem Value="Value2" Text="Text2"></asp:ListItem>
<asp:ListItem Value="Others" Text="Others"></asp:ListItem>
</asp:ListBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("conditions") %>' Font-Size="10px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Any ideas?
You need to access the ListBox in the RowDataBound event of the GridView
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow and in edit mode
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) > 0)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//use findcontrol to locate the listbox and cast it
ListBox lb = e.Row.FindControl("dd_conditions") as ListBox;
//loop all the items in a listbox
for (int i = 0; i < lb.Items.Count; i++)
{
//check the values and set the Selected property
if (lb.Items[i].Value == row["conditions"].ToString())
{
lb.Items[i].Selected = true;
}
}
}
}

How to bind string to grid?

I want to display data in gridview based on check box selection from another grid view. The given below code getting values into from first gridview based on check box selection. I want to bind that values into second grid. Help me to find a proper solution. Thank you.
Code :
protected void btnAssign_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string[] EmpId = new string[] { row.Cells[0].Text };
string[] EmpName = new string[] { row.Cells[1].Text};
// I want to display emp id and emp name on gridview 2 based on check box selection. How can I do. Help me to find a proper solution
GridView2.DataSource = EmpId;
GridView2.DataBind();
}
}
}
}
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="Employee Name" ReadOnly="True" SortExpression="FirstName" />
<asp:TemplateField HeaderText="Select" SortExpression="Select">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server"> </asp:GridView>
The given below image is showing data in grid view based on drop-down selection. After that I want to select some rows and click assign then I have to display the selected rows in new gridview.
Image :
If you don't already have a strong type defined to represent your selected Employee, you could create a Dictionary to store your selected employees. Upon completing your iteration over GridView1's rows to get the selected employees, you could use the dictionary as the datasource for GridView2 and bind to the Key and Value of each entry.
protected void btnAssign_Click(object sender, EventArgs e)
{
Dictionary<int, string> selectedEmployees = new Dictionary<int, string>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
selectedEmployees.Add(int.Parse(row.Cells[0].Text), row.Cells[1].Text);
}
}
}
if (selectedEmployees.Any())
{
gridView2.DataSource = selectedEmployees;
gridView2.DataBind();
}
}
UPDATE: Updated the code to account for the exception that you were receiving with the sample code provided

How to change the text on certain condition in GridView?

I want to change the text/value of a cell in certain condition in GridView. I have a cell that return 'P', 'A', 'R' when I bind the Gridview from database. I want to show 'Pending' in case of 'P', 'Approved' in case of 'A' and 'Rejected' in case of 'R' in the dropdown with the update button. I want to change the status of a record.
How can I change the text AND do my required task at the time of Binding of data.
<asp:TemplateColumn>
<HeaderStyle CssClass="bgB white p5 b treb ttu w10" />
<HeaderTemplate>
<asp:Label ID="lblstatus" runat="server" Text="Status"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblrmastatus" runat="server" Text='<%# Bind("RMA_STATUS") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
A way to solve this is to handle the RowDataBound event. It is raised once per row (also header and footer rows, so you need to filter for rows of type DataRow). You can use it to adjust the data that are displayed or the way they are displayed. Also you can set the values of a DropDown in the event. See the link for a sample.
In order to add the DropDown-column to the GridView, use a TemplateColumn and put the DropDown into the ItemTemplate. Access the corresponding cell in the RowDataBound event handler. Use the FindControl method to retrieve the DropDown control and set its values.
The following sample shows how to set the Label and the DropDownList programmatically:
GridView
The GridView shows both the original status and a new status with the long text, a DropDownList and a command column to update the data.
<asp:GridView ID="gdv" runat="server"
OnRowDataBound="gdv_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RMAStatus" HeaderText="Original RMA Status" />
<asp:TemplateField HeaderText="Adjusted RMA Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
Code-behind
In Code-behind, I've defined a class called DataClass that contains the data (you can also use a DataTable, but for the sample it was easier to use a class to generate some data). Also, a dictionary contains the mappings from the short status to the long text.
In Page_Load, the dictionary is set up and if it is no PostBack, the data are bound.
Finally, in gdv_RowDataBound, the label is set for each row and the DropDownList is initialized. Please note that the Label and the DropDownList for the row are retrieved by using FindControl.
public class DataClass
{
public string RMAStatus { get; set; }
}
private readonly Dictionary<string, string> rmaStatusMappings = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
rmaStatusMappings.Add("R", "Rejected");
rmaStatusMappings.Add("A", "Approved");
rmaStatusMappings.Add("P", "Pending");
if (!IsPostBack)
{
var data = new DataClass[] {
new DataClass() { RMAStatus = "P" },
new DataClass() { RMAStatus = "A" },
new DataClass() { RMAStatus = "R" },
new DataClass() { RMAStatus = "P" },
};
gdv.DataSource = data;
gdv.DataBind();
}
}
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var rowStatus = ((DataClass)e.Row.DataItem).RMAStatus;
// Set label to long status
var lblStatus = e.Row.Cells[1].FindControl("lblStatus") as Label;
if (lblStatus != null)
lblStatus.Text = rmaStatusMappings[rowStatus];
// Set drop down items
var ddlStatus = e.Row.Cells[2].FindControl("ddlStatus") as DropDownList;
if (ddlStatus != null)
{
ddlStatus.DataTextField = "Value";
ddlStatus.DataValueField = "Key";
ddlStatus.DataSource = rmaStatusMappings;
ddlStatus.DataBind();
ddlStatus.SelectedValue = rowStatus;
}
}
}
Let me know in the comments if you have any questions.

Setting a Textbox value within a GridView template field

Within my load method of my page i want to set the Textbox in a templatefield to a value.
Here is my current source code showing my template field textbox item 'txtQuan':
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTotalRate" Text="Qty:" runat="server" />
<asp:TextBox ID="txtQuan" Height="15" Width="30" runat="server" />
<asp:Button ID="addButton" CommandName="cmdUpdate" Text="Update Qty" OnClick="addItemsToCart_Click" runat="server" />
</ItemTemplate>
</asp:TemplateField>
And this is how im trying to set the TextBox value:
string cartQty = Qty.ToString();
((TextBox)(FindControl("txtQuan"))).Text = cartQty;
Im currently receiving a 'nullRefernceException error'.
Use the RowDataBound event to do that. You can look that up on the internet. The arguments to that event handler gives you easy access to each row. You can also loop through the rows using var rows = myGridView.Rows
var rows = myGridView.Rows;
foreach(GridViewRow row in rows)
{
TextBox t = (TextBox) row.FindControl("txtQuan");
t.Text = "Some Value";
}
For the event: GridView RowDataBound
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t = (TextBox) e.Row.FindControl("txtQuan");
t.Text = "Some Value";
}
}
((TextBox)grdviewId.Row.FindControl("txtQuan")).Text=cartQty;

Dynamically added controls missing during GridView RowUpdating

I have a GridView with a TemplateField column that I put PlaceHolder controls in. During the DataBound event for the GridView I dynamically add a few CheckBoxes to the PlaceHolder. That works fine and displays as expected.
My problem is that during the RowUpdating event the PlaceHolder contains no controls; my CheckBoxes are missing. I also noticed that they're missing during the RowEditing event.
I want to be able to get the values of the CheckBoxes during the RowUpdating event so I can save them to the database.
Here's some example code. I've trimmed out a lot to reduce size, but if you want to see specifics just ask and I'll be happy to add more.
HTML:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
ondatabound="gridView_DataBound" onrowupdating="gridView_RowUpdating"
onrowediting="gridView_RowEditing" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
<EditItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="updateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
// This method works fine, no obvious problems here.
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder)row.FindControl("countriesPlaceHolder");
// Create a CheckBox for each country and add it to the PlaceHolder
foreach (Country country in this.Countries)
{
bool isChecked = holidays.ElementAt(i).Countries.Any(item => item.ID == country.ID);
var countryCheckBox = new CheckBox
{
Checked = isChecked,
ID = country.Abbreviation + "CheckBox",
Text = country.Abbreviation
};
placeHolder.Controls.Add(countryCheckBox);
}
}
}
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = gridView.Rows[e.NewEditIndex].FindControl("countriesPlaceHolder").Controls;
gridView.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = ((PlaceHolder)gridView.Rows[e.RowIndex].FindControl("countriesPlaceHolder")).Controls;
// This is where I'd grab the values from the controls, create an entity, and save the entity to the database.
gridView.EditIndex = -1;
BindData();
}
This is the article that I followed for my data binding approach: http://www.aarongoldenthal.com/post/2009/04/19/Manually-Databinding-a-GridView.aspx
You need to call your BindData() method on page load.
"Dynamic controls or columns need to be recreated on every page load, because of the way that controls work. Dynamic controls do not get retained so you have to reload them on every page postback; however, viewstate will be retained for these controls."
See Cells in gridview lose controls on RowUpdating event
Also in the article you linked, there is an ItemTemplate and an EditItemTemplace because they have different displays, i.e. read only and editable. Yours are the same so I think you could simplify your design:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ondatabound="gridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" Text="Edit" onclick="editButton_Click" ></asp:LinkButton>
<asp:LinkButton ID="updateButton" runat="server" Text="Update" onclick="updateButton_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder) row.FindControl("countriesPlaceHolder");
var countryCheckBox = new CheckBox
{
Checked = true,
ID = "auCheckBox",
Text = "Aus",
Enabled = false
};
placeHolder.Controls.Add(countryCheckBox);
var editButton = (LinkButton)row.FindControl("editButton");
editButton.CommandArgument = i.ToString();
var updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.CommandArgument = i.ToString();
updateButton.Visible = false;
}
}
protected void editButton_Click(object sender, EventArgs e)
{
LinkButton editButton = (LinkButton) sender;
int index = Convert.ToInt32(editButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.Visible = true;
editButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
checkbox.Enabled = true;
// Get value and update
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
LinkButton updateButton = (LinkButton)sender;
int index = Convert.ToInt32(updateButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton editButton = (LinkButton)row.FindControl("updateButton");
editButton.Visible = true;
updateButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
// Get value and update
checkbox.Enabled = false;
}
}
If you want to be it enabled from the get go, just remove the enabled checks and you can delete your edit button.
Hope that helps.

Categories