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
Related
I have Gridview with 10 Rows each row have 2 columns which is Textbox and Checkbox.
what i have to do is have to enter textbox Value as 1000 and i Clicked the Checkbox at first Row then value must go to Textbox of Second row and i clicked checkbox of Second Row then value must be go to third row of Textbox and so on.
i tried this,
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow grid = ((GridViewRow)txt.Parent.Parent.Parent);
TextBox txtIntro = (TextBox)txt.FindControl("txtintroId");
}
here i get the 1st row Value but How do i pass this to second Row.
Assist me
Here is full working code(as per your requirement )
Create a gridview like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("txtcolumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Add a function in code behind C#
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
int rowNo=0;
foreach (GridViewRow GV1 in GridView1.Rows)
{
rowNo++;//
if (rowNo < GridView1.Rows.Count) //Checking that is this last row or not
{
//if no
CheckBox chkbx= (CheckBox)GV1.FindControl("CheckBox1");
TextBox curenttxtbx = (TextBox)GV1.FindControl("TextBox1");
if (chkbx.Checked == true )
`{
int nextIndex = GV1.RowIndex + 1;//Next row
TextBox txtbx = (TextBox)GridView1.Rows[nextIndex].FindControl("TextBox1");
txtbx.Text = curenttxtbx.Text;
}
}
//if yes
else
{
//For last row
//There is no next row
}
}
}
And i used this data table as data source
DataTable table = new DataTable();
table.Columns.Add("txtcolumn", typeof(string));
table.Rows.Add("1");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("3");
table.Rows.Add("32");
table.Rows.Add("32");
I tested this code it is working as per your requirement. (And SORRY for this bad formatting. i will do it later or please some body correct the formating :))
I have a problem with my code. I need enable or disable a HyperLink in the RowDataBound event in an ASP.NET GridView based on a value extracted from the database.
If the value of field File of my database is not null, the HyperLink is visible otherwise not. In GridView, I don't have planned to show the value of field File.
I've tried using these solution without success, because I have this error.
Compiler Error Message: CS1502: The best overloaded method match for 'string.IsNullOrEmpty(string)' has some invalid arguments
Here is my code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink Srl = (HyperLink)e.Row.FindControl("Srl");
foreach (string color in colorList)
{
if (!string.IsNullOrEmpty(DataBinder.Eval(e.Row.DataItem, "File")))
{
Srl.Visible = true;
}
}
}
}
DataBinder.Eval returns an object. You need to convert that to a String.
Try this:
if (!string.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "File"))))
{
Srl.Visible = true;
}
<asp:GridView ID="gvList" runat="server" Width="100%" AutoGenerateColumns="False" AllowPaging="false">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" />
<asp:HiddenField ID="hfSLNO_BARCODE" runat="server"
Value='<%#Bind("SLNO_BARCODE") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Use asp:HiddenField for File value and use this in row data bound event.
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink Srl = (HyperLink)e.Row.FindControl("Srl");
foreach (string color in colorList)
{
string str = (string)DataBinder.Eval(e.Row.DataItem, "File");
//then you can check
if (!String.IsNullorEmpty(str ))
{
Srl.Visible = true;
}
}
}
}
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
before I asked this I did some checking around to make sure that this doesn't turn out to be a duplicate and ways to get the row values from a row that has a checkbox in its template field...but I can't seem to get it working...So far I have tried
protected void Page_Load(object sender, EventArgs e)
{
Entities NW = new Entities();
var customers =
from c in NW.Customers
where (c.ContactName.StartsWith("Ma") || c.ContactName.StartsWith("An")
|| c.ContactName.StartsWith("T")
|| c.ContactName.StartsWith("V")
)
orderby c.ContactName ascending
select new
{
c.CustomerID,
c.ContactName,
c.CompanyName,
c.City
};
gv1.DataSource = customers.ToList();
gv1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gv1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("CB") as CheckBox);
if (chkRow.Checked)
{
Label1.Text = row.Cells[2].Text;
}
}
}
}
I have stepped through the button click event and when it gets to
if (chkRow.Checked)
its showing as null and skips over it..
my markup is
<asp:GridView ID="gv1" runat="server">
<HeaderStyle BackColor="SkyBlue" />
<AlternatingRowStyle BackColor="Yellow" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CB" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
when I look at the source after I run, the checkboxes are all named differently than what I gave them the ID of "CB", attached is the pic of the source when its running
I am not sure what I am doing wrong with this
Your GridView should have more columns, because you are referencing Cell[2] in your code.
You might try to use row object to look for your control:
CheckBox chkRow = (row.FindControl("CB") as CheckBox);
I know there are a bunch of questions with detailed instructions on exporting from gridview to excel, but I can't find my particular situation.
I have a gridview that displays records with five fields from a search. Users can check in a checkbox any number of records. On a button click, I can successfully export only the checked records to Excel. Export is as HTML. I'm using the technique from Matt Berseth here: http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
I added a check for whether the record was checked by the user and this works fine.
But I have a requirement that for the checked records that are exported, the users want to see the entire records (i.e. all fields in just the selected records).
What is a good strategy to accomplish this?
I've tried retrieving all fields in the gridview and setting all but the five desired fields to not visible. Then in the export button click event, setting the fields to visible and rebinding. No luck there.
Thanks for any help.
Sounds like you should loop through the rows to see which are checked.
foreach (GridViewRow row in gridView.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = row.FindControl("CheckBoxID") as CheckBox;
if(cb != null && cb.Checked)
{
// Logic here.
}
}
From there, you can export to excel using several different mechanisms, depends on your needs. One I've used in the past if you just need xls files is NPOI -- it's open source and provides a decent framework for it. Here is a link to their site:
http://npoi.codeplex.com/
-- EDIT
After reading your comments, maybe this will help.
ASPX Code:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Checkbox Column">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxID" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Visible Column">
<ItemTemplate>
<asp:Label ID="lblVisibleColumn" runat="server" Text='<%# Eval("VisibleColumn")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hidden Column" Visible="false">
<ItemTemplate>
<asp:Label ID="lblHiddenColumn" runat="server" Text='<%# Eval("HiddenColumn")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
Backend Code:
public class MyDataColumn
{
public string visibleColumn { get; set; }
public string hiddenColumn { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dataTable = new DataTable();
List<MyDataColumn> dataColumns = new List<MyDataColumn>();
for (int i = 0; i < 10; i++)
{
dataColumns.Add(new MyDataColumn()
{
visibleColumn = string.Format("Visible Column {0}", i),
hiddenColumn = string.Format("Hidden Column {0}", i)
});
}
gridView.DataSource = dataColumns;
gridView.DataBind();
}
}
protected void btnExport_Click(object sender, EventArgs e)
{
List<MyDataColumn> dataColumnsToExport = new List<MyDataColumn>();
foreach (GridViewRow row in gridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = row.FindControl("CheckBoxID") as CheckBox;
if (cb != null && cb.Checked)
{
Label lblVisibleColumn = row.FindControl("lblVisibleColumn") as Label;
Label lblHiddenColumn = row.FindControl("lblHiddenColumn") as Label;
dataColumnsToExport.Add(new MyDataColumn()
{
visibleColumn = lblVisibleColumn.Text,
hiddenColumn = lblHiddenColumn.Text
});
}
}
}
GridView gridViewToExport = new GridView();
gridViewToExport.DataSource = dataColumnsToExport;
gridViewToExport.DataBind();
//Do Something With gridViewToExport
//GridViewExportUtil.Export("GridView.xls", gridViewToExport);
}
And this should be easy to convert to a DataTable if needed -- I used my own class to make it shorter code.