Not properly set Data in GridView - c#

i'm trying retrieve data from database and dispay in gridview. for create Header i'm using HeaderTemplet Tag. but in gridview always first column of employee id is blank.
my code is as under of aspx page:
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<tr>
<th style="padding: 2.5px; width: 10%;" >eid</th>
<th style="padding: 2.5px; width: 55%;" >First Name</th>
<th style="padding: 2.5px;" >Last Name</th>
</HeaderTemplate>
</asp:TemplateField>
<asp:BoundField DataField="idemp" />
<asp:BoundField DataField="fname" />
<asp:BoundField DataField="lname" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2" runat="server" Width="99%" GridLines="Both" AutoGenerateColumns="false" CssClass="ChildGrid">
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
code behind:
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the GridView.
bindGridview();
}
}
public void bindGridview()
{
DataTable dt = new DataTable();
string constr = #"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand cmd = new MySqlCommand("select idemp,fname,lname from emp", con);
con.Open();
MySqlDataReader dtreader = cmd.ExecuteReader();
dt.Load(dtreader);
if (dt.Rows.Count >0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
//RowDataBound Event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking the RowType of the Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = new DataTable();
string constr = #"server=127.0.0.1;user id=root;pwd=n0711p2010p;database=emp";
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Open();
GridView child_gridview = (GridView)e.Row.FindControl("GridView2");
String CountryId = (e.Row.RowIndex+1).ToString();
MySqlCommand cmd = new MySqlCommand("select salary,post from emp where idemp="+CountryId, con);
MySqlDataReader dtreader = cmd.ExecuteReader();
dt.Load(dtreader);
if (dt.Rows.Count > 0)
{
child_gridview.DataSource = dt;
child_gridview.DataBind();
}
}
}
}
}
}
and output is as under:
first column of gridview is always empty.when using HeaderTemplet tag.
and i want to achieve like this.

If you want the nested GridView to span multiple columns, you have to do that in the RowDataBound of the parent GridView. In there you can set the colspan and remove the last 2 cells.
So if you have a GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<%# Eval("Id") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saldy">
<ItemTemplate>
<asp:GridView ID="NestedGrid" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
</asp:TemplateField>
</Columns>
</asp:GridView>
And the RowDataBound event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a normal datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//use findcontrol to locate the nested gridview
GridView gv = e.Row.FindControl("NestedGrid") as GridView;
//bind data to the nested grid
gv.DataSource = source;
gv.DataBind();
//set the column span to 3 on the cell that has the nested gridview
e.Row.Cells[2].ColumnSpan = 3;
//hide the last 2 cells
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].Visible = false;
}
}
The only problem is that the cells of the parent and child do not match in width, so you may need to set a fixed width for those columns.

Seems like you are retrieving the data just fine but not displaying it properly.
You are mistakenly using TemplateField to define headers.
You can simply do the following:
<asp:GridView ID="GridView1" runat="server" Width="99%" GridLines="Both" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="idemp" headertext="Employee ID" />
<asp:BoundField DataField="fname" headertext="First Name" />
<asp:BoundField DataField="lname" headertext="Last Name" />
</Columns>
</asp:GridView>
As you can see the Header names are defined right in bound column.
Enjoy, and let me know if still having issue

Related

How to add checkboxes in GridView Cells on ASP.NET

So I am new to ASP.NET, and am having trouble finding this on the web too. What I am trying to accomplish is adding checkboxes inside the cells of the table I would like to create. Currently, the code I have implemented presents a whole new check box column, as show below:
<asp:GridView runat="server" ID="Gv1">
<Columns>
<asp:templatefield HeaderText="Check Box">
<itemtemplate>
<asp:checkbox ID="cb" runat="server"></asp:checkbox>
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
Again, what I am trying to accomplish is make each of the empty cells on the grid consist of a check box. Any help would be greatly appreciated.
You don't share how many columns you need?
But, lets say we want 20 columns, and 10 rows deep.
So, we have this markup:
<asp:GridView ID="GridView1" runat="server" CssClass="table"
OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
And our code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
DataTable rstData = new DataTable();
//ADD 20 columns
int i;
int j;
for (i = 1;i <= 20;i++)
rstData.Columns.Add("C" + i,typeof(bool));
// now add 10 rows
for (i = 1;i <= 10;i++)
{
DataRow OneRow = rstData.NewRow();
// lets check the first 5 columns
for (j = 0; j < OneRow.Table.Columns.Count; j++)
OneRow[j] = (j <= 4);
rstData.Rows.Add(OneRow);
}
GridView1.DataSource = rstData;
GridView1.DataBind();
}
We VERY unfortunately have to deal with default check boxes on a grid are read only and not enabled. So, in the on- row data bound even, we have to add this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell c in e.Row.Cells)
{
CheckBox ck = c.Controls[0] as CheckBox;
ck.Enabled = true;
}
}
}
And now we get this:
Edit: Example with check box(s) from data table.
So, if you need to setup some check boxes in the gv, then I suggest you actually add the check boxes as columns and use REAL asp.net check box controls.
So, with this gv markup:
<asp:GridView ID="GridView1" runat="server" class="table"
AutoGenerateColumns="false" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkActice" runat="server"
Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now our code behind to load above is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName ";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rst;
GridView1.DataBind();
}
}
}
And now we see/get this:

How to remove a row from gridview on Row Command?

I have a grid view where data is dyanmically added. I need an onRowCommand where the selected row will be deleted. I need the row to be deleted only from the grid view.
protected void LoadDataTable()
{
string header = lblHeader.Text;
string aa = tv.SelectedNode.Parent.Value;
string child = tv.SelectedNode.Text;
string parent = tv.SelectedNode.Parent.Text;
var dt = new DataTable();
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("TargetGLId");
dt.Columns.Add("TargetHead");
dt.Columns.Add("Parent");
dt.Columns.Add("Header");
foreach (GridViewRow row in gvBudgetSetup.Rows)
{
var lblheader = (Label)row.FindControl("lblHeader");
var lblparticular = (Label)row.FindControl("lblParticular");
var lblGlId = (Label)row.FindControl("lblGLId");
var lblparent = (Label)row.FindControl("lblParent");
var dr = dt.NewRow();
dr["TargetHead"] = lblparticular.Text;
dr["TargetGLID"] = lblGlId.Text;
dr["Parent"] = lblparent.Text;
dr["Header"] = lblHeader.Text;
dt.Rows.Add(dr);
}
var dr1 = dt.NewRow();
dr1["TargetHead"] = child;
dr1["TargetGLID"] = tv.SelectedValue;
dr1["Parent"] = parent;
dr1["Header"] = header;
dt.Rows.Add(dr1);
gvBudgetSetup.DataSource = null;
gvBudgetSetup.DataBind();
gvBudgetSetup.DataSource = dt;
gvBudgetSetup.DataBind();
}
I have tried this code to delete the row but it is not working.
protected void gvBudgetSetup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete1")
{
// gvBudgetSetup.DeleteRow(e.Row.RowIndex);
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
}
}
This is the Gridview created. The gridview is not connected to any database. The data in the gridview is added from the back-end codes.
<asp:GridView ID="gvBudgetSetup" runat="server" CssClass="table1" AutoGenerateColumns="false" ShowFooter="true" OnSelectedIndexChanged="gvBudgetSetup_SelectedIndexChanged"
ShowHeaderWhenEmpty="true" OnRowDataBound="gvBudgetSetup_RowDataBound" OnRowCommand="gvBudgetSetup_RowCommand" OnRowDeleting="gvBudgetSetup_RowDeleting" Width="100%">
<FooterStyle CssClass="GridFooter" />
<RowStyle CssClass="GridItem" />
<columns>
<asp:TemplateField HeaderText="Sn">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GL Id">
<ItemTemplate>
<asp:Label ID="lblGLId" runat="server" Text='<%# Bind("TargetGLID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:Label ID="lblHeader" runat="server" Text='<%# Bind("Header") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Parent">
<ItemTemplate>
<asp:Label ID="lblParent" runat="server" Text='<%# Bind("Parent") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Child">
<ItemTemplate>
<asp:Label ID="lblParticular" runat="server" Text='<%# Bind("TargetHead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Delete" CommandName="Delete1"
ID="lnkDelete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</columns>
<EmptyDataTemplate>
"There are no data to display..."
</EmptyDataTemplate>
</asp:GridView>
Better way to do is have a flag in the data source that one row is flagged(deleted) and bind it again. To delete a datarow from a GridViewEvent, you have to re bind the datasource again.
Introduce a Flag column in your data source
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//Update the flag in datasource using the CommandArgument value
//Bind the datasource again.
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
Use this updated code

How can i hold gridview row selected values into a string in asp.net

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;
}
}
}

Container.DisplayIndex not working with paging in ASP.NET

I have a gridview that is bound with data from code behind. Paging is applied in gridview. Everything works fine. For showing Row-Index i use Container.DisplayIndex.
When i go to next page through paging, every time gridview bind perfectly but DisplayIndex start with 1 to pagesize. I don't know what is wrong with the code.
Here is Asp.NET Code:
<asp:GridView runat="server" ID="dlAddress" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="dlAddress_PageIndexChanging" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DisplayIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Center"/>
</asp:GridView>
C# Code:
public void bindGridView()
{
DBACon.Open();
SqlCommand Cmd = new SqlCommand("getAddresses", DBACon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(DS);
dlAddress.DataSource = DS;
dlAddress.DataBind();
}
protected void dlAddress_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dlAddress.PageIndex = e.NewPageIndex;
bindGridView();
}
Here,
ASPX:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="False" DataKeyNames="AddressID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="RowNumber">
<ItemTemplate>
<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

How to bind 2 databse tables to gridview and one as dropdown

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="301px" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
<%-- <asp:BoundField DataField="StudentDOB" HeaderText="StudentDOB" SortExpression="StudentDOB" />--%>
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/Employee/EmployeeEditPage.aspx?StudentID={0}", Eval("StudentID"))%>'> Edit</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
above is my design:
below I wrote my code for to display the database, which have table departmenttable and another table studenttable to show the values into the grid. in department table I have departmentname(dept_name)
which should come in dropdown inside the gridview..but it showing error..pls help..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(DataBase.GetConnection());
con.Open();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList = (DropDownList)e.Row.FindControl("dept_name");
//bind dropdownlist
DataTable dt = con.GetData("select dept_name from dbo.DepartmentTable");
ddList.DataSource = dt;
ddList.DataTextField = "dept_name";
ddList.DataValueField = "DeptName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["DeptName"].ToString();
con.Close();
GridView1.DataBind();
}
}
}
For binding dropdownlist in GriView first you need to find it by its id. In your sample code, you are trying to find something which is not dropdownlist.
Try this,
DropDownList ddList = (e.Row.FindControl("DropDownList1") as DropDownList);
if(ddList != null)
{
//your code
}

Categories