I have two tables in my SQL Server database (one for adding subjects and other for adding marks obtained in those subjects based on class). I want to make marks entry just like excel entry so I'm fetching student names in the first column of the gridview and populating textboxes in other columns of the gridview to enter the marks as shown here:
Now the problem is that if student 'A' of class 10 has selected 4 subjects and student 'B' of class 5 has selected 5 subjects, how do I implement the marks entry module being said that student 'A' gets only 4 textboxes and subject columns in the gridview and student 'B' gets only 5 textboxes.
This is my Aspx markup:
<asp:GridView ID="grdMarksEntry" GridLines="None" runat="server"
AutoGenerateColumns="false"
CssClass="table table-hover table-responsive table-bordered" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="Sl. No.">
<ItemTemplate>
<%#Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Name of the student" />
<asp:TemplateField HeaderText="Subject 1">
<ItemTemplate>
<asp:TextBox ID="txtSub1" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject 2">
<ItemTemplate>
<asp:TextBox ID="txtSub2" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject 3">
<ItemTemplate>
<asp:TextBox ID="txtSub3" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject 4">
<ItemTemplate>
<asp:TextBox ID="txtSub4" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject 5">
<ItemTemplate>
<asp:TextBox ID="txtSub5" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject 6">
<ItemTemplate>
<asp:TextBox ID="txtSub6" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my c# code behind:
private void bindgrd()
{
string constr = ConfigurationManager.ConnectionStrings["DatabaseConnect"].ConnectionString;
using (SqlConnection StudMarksCon = new SqlConnection(constr))
{
using (SqlCommand StudMarksCmd = new SqlCommand("select distinct name from studentregistration where class='" + drpClass.SelectedItem.ToString() + "' and div='" + drpDiv.SelectedItem.ToString() + "'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
StudMarksCmd.Connection = StudMarksCon;
sda.SelectCommand = StudMarksCmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdMarksEntry.DataSource = dt;
grdMarksEntry.DataBind();
}
}
}
}
You need to create the number of text boxes dynamically based on number of subjects that the student selected.
Related
I am having database table with subject,faulty,hour.In the hour value am storing like 1,2,3,4 and 5 in the database.I want to disable the already clicked check box but in my result it is blocking the whole row not the particular check box.help me out from these problem.I have uploaded my sample code and database schema below
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="datee" HeaderText="Day/Hour" SortExpression="datee" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Checked='<%# Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=1) %>' OnCheckedChanged="chkHour1_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="ChkColumn2" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=2) %>' OnCheckedChanged="chkHour2_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn3" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=3) %>' OnCheckedChanged="chkHour3_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn4" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=4) %>' OnCheckedChanged="chkHour4_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn5" runat="server"/>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=5) %>' OnCheckedChanged="chkHour5_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
con.Open();
SqlDataAdapter cmd = new SqlDataAdapter("select DISTINCT datee,hour from tblfac order by datee", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I clicked only 1 check box value but it is blocking the whole column.help me out from the problem
If I'm understanding the question correctly, the problem is that all five checkboxes in the row are checked, regardless of what the value of hour is. This is because you are using
Checked='<%#Convert.ToBoolean((int)Eval("hour"))%>'
to set the value of the checkbox. You are converting the integer value of hour to a boolean value. Convert.ToBoolean will translate any non-zero integer to true, so as long as hour isn't zero, the checkbox will be checked.
Working example:
Creating datasource in code-behind:
DataTable dt = new DataTable("dt");
dt.Columns.Add("datee", typeof(string));
dt.Columns.Add("hour", typeof(int));
dt.Rows.Add("06-Jul-15 12:00:00 AM",1);
dt.Rows.Add("07-Jul-15 12:00:00 AM",2);
dt.Rows.Add("08-Jul-15 12:00:00 AM",3);
dt.Rows.Add("09-Jul-15 12:00:00 AM",4);
dt.Rows.Add("10-Jul-15 12:00:00 AM",5);
GridView1.DataSource = dt;
GridView1.DataBind();
Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="datee" HeaderText="Day/Hour" SortExpression="datee" />
<asp:TemplateField HeaderText="Hour1">
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Checked='<%# Convert.ToBoolean((int)Eval("hour")==1)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=1) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==2)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=2) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==3)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=3) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==4)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=4) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Checked='<%#Convert.ToBoolean((int)Eval("hour")==5)%>' Enabled='<%# Convert.ToBoolean((int)Eval("hour")!=5) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Results showing only one box checked, and that box disabled:
I have a grid view it has 3 drop down lists and 3 text boxes in template field. On the top of the grid view i have two text boxes( text box 1 and 2) which initilize there values when page is loaded. i also have 3 buttons for add new row , save , search. I want my grid view to show data from database when search button is clicked i.e select * from table where text box 1 and 2 equal to some thing. My HTML looks like.
AutoGenerateColumns="false" onselectedindexchanged="Gridview1_SelectedIndexChanged" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Item name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="119px"
DataTextField = "Item_name" Text='<%# Bind("Item_name") %>' DataValueField="Item_name"
AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub item">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="119px"
AppendDataBoundItems="true"
DataValueField = "Sub_item" Text='<%# DataBinder.Eval(Container, "DataItem.Sub_item") %>' DataTextField = "Sub_item"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Location") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Permit number">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Permit no") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Applied">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
Height="25px" Width="119px"
DataTextField="Text" AppendDataBoundItems="true" Text='<%# DataBinder.Eval(Container, "DataItem.Applied") %>' DataValueField="Value" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Revision">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Revision") %>' ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="Save_Click" />
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" />
<asp:Button ID="search" runat="server" Text="Search" OnClick="Search_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
on my search button click i have this code
if (TextBox4.Text != null && TextBox5.Text != null)
{
string job = TextBox4.Text.ToString();
string leg = TextBox5.Text.ToString();
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
Response.Write(job);
Response.Write(leg);
conn.Open();
SqlCommand comand = new SqlCommand("SELECT * from Billing_heads where job# = '" + job + "' AND leg#='" + leg + "' ", conn);
// try
//{
SqlDataAdapter adp = new SqlDataAdapter(comand);
DataSet ds = new DataSet();
adp.Fill(ds);
//gvPros is the ID of GridView.
Gridview1.DataSource = ds;
Gridview1.DataBind();
Please help me that how can i bind my gridview because in Text='<%# Bind("Item_name") %>' property it saying the column name it says property with name "coloumn name " does not exists please help
I want to update only selected row from my grid view when i press linked button but it is not working on my end .
Here is my Design Page
<asp:GridView ID="grdCompanyUsers" runat="server"
DataKeyNames="id_company_user,nm_company_username"
AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-
BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images
/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CompUserID" runat="server" Width="15"
Text='<%#Eval("id_company_user")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="companyusername" runat="server" Width="51"
Text='<%#Eval("nm_company_username")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compName" runat="server" Width="56" Text='<%#Eval("nm_company_name")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compDesc" runat="server" Width="129" Text='<%#Eval("nm_company_desc")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compEmail" runat="server" Width="103px"
Text='<%#Eval("nm_company_email_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compAddress" runat="server" Width="153px"
Text='<%#Eval("nm_company_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxStatus" runat="server" Width="15px" Enabled="false"
Text='<%#Eval("ind_active")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false"
CommandArgument='<%#Eval ("id_company_user")%>'
OnClick="btnEdit_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDeny" Font-Underline="false" CommandName="Deny"
CommandArgument='<%# Eval("id_company_user") %>'
OnClick="btnDeny_Click">Deny</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my code behind the aspx page
protected void btnEdit_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int i = Convert.ToInt32(row.RowIndex);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update ref_registration_company_user
set ind_active=1 where id_company_user=id_company_user", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is Design View :
I just want that only selected row should be affected in database.
I will be thank full for help.
you need to set the id_company_user value in your sql statement. use parameters as below.
SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=#id_company_user", conn);
cmd.Parameters.AddWithValue("#id_company_user", id);
you need to get current row id_company_user value check below SO question and answer, you can use
OnRowCommand of GridView and CommandArgument property
GridView: Get datakey of the row on button click
<asp:GridView ID="grdCompanyUsers" runat="server" DataKeyNames="id_company_user,nm_company_username" AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound"
OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false" CommandArgument='<%#Eval ("id_company_user")%>' CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id= int.Parse(e.CommandArgument);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=id_company_user", conn))
{
cmd.Parameters.AddWithValue("#id_company_user", id);
cmd.ExecuteNonQuery();
}
}
}
Can you please check once your update query where clause,
Check the sqlDataSource control for this problem, you can add the select and update command for populate and update rows your GridView on there.
Maybe this example could be you useful
http://asp-net-example.blogspot.mx/2008/12/aspnet-gridview-and-sqldatasource.html
I have a Gridview and inside I have another one nested GridView. When I press a plus button the nested GridView expands using a JavScript. The nested GridView expands on edit mode using TextBox controls. So when the user types on a TextBox would have the ability to update the cell using an update button. My problem is that when I press the update button the update occurs but not how I would expected. If for example the initial value of a cell was “My name is Peter” and I have done the edit “I don’t have a name” The new value that will be saved is exactly this: “My name is Peter, I don’t have a name”. The databind of the nested GridView occurs on the parent GridView DataBound event.
My code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="gridView_PageIndexChanging"
AutoGenerateColumns="False" DataKeyNames="myitemID"
OnRowDataBound="GridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="../plus.png" />
<asp:GridView ID="nestedGridView" runat="server"
AutoGenerateColumns="False"
DataKeyNames="mynestedID">
<Columns>
<asp:TemplateField HeaderText="nestedID" Visible="false" ItemStyle-Width="20%"
SortExpression="nesteditemID">
<ItemTemplate>
<asp:Label ID="nesteditemID" runat="server" Text='<%# Bind("nesteditemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="20%"
SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="name" TextMode="MultiLine" Width="80%" Rows="3" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Panel ID="mypanel" runat="server">
<table>
<tr>
<td>
<asp:ImageButton ID="ImageButton2" OnClick="updatename_Click" ImageUrl="~/images/update.jpg" Width="15px" Height="15px" runat="server"></asp:ImageButton>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="myitemID" InsertVisible="False"
SortExpression="myitemID" Visible="False">
<ItemTemplate>
<asp:Label ID="myitemID" runat="server" Text='<%# Bind("myitemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ItemName" ItemStyle-Width="20%"
SortExpression="ItemName">
<ItemTemplate>
<asp:Label ID="ItemName" runat="server" Text='<%# Bind("ItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
cs code:
protected void updatename_Click(object sender, EventArgs e)
{
GridViewRow masterrow = (GridViewRow)(sender as Control).Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent;
GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent.Parent;
int index = row.RowIndex;
int mi = masterrow.RowIndex;
int i = index;
GridView nestedGridView = (GridView)GridView1.Rows[mi].FindControl("nestedGridView");
Label nestedID = (Label)nestedGridView.Rows[index].FindControl("nestedID");
int sbid = Convert.ToInt32(nestedID.Text);
TextBox name = (TextBox)nestedGridView.Rows[index].FindControl("name");
string myname = Convert.ToString(name.Text);
//update name with the new value
Nesteditem updatenesteditem = mylinqobjects.Nesteditems.Single(p => p.nesteditemID == sbid);
if (!string.IsNullOrEmpty(myname))
{
updatenesteditem.nesteditemName = myname;
mylinqobjects.SubmitChanges();
}
}
Replaced the current text by removing the old one.
string myname = name.Text.Substring(name.Text.LastIndexOf(",")+1);
Tried all possiblities, but due nested grid view rendering and its restrictions, we could do only like above.
Any others solutions, please provide.
I have the following database design:
Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut
And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. IsActive is a flag that indicates if the employee is available or in an assignment. I made it as a checkbox and the column should show two values; Active and Inactive. In the Edit mode, the Checkbox will be displayed. If it is checked, then it means the employee is avaiable, otherwise it is inactive.
I wrote the code and everything works fine, but now I am facing two problems and I don't know how to make them work with my code.
The GridView shows True or False instead of Active and Inactive and
I don't know why.
In the Edit mode, the checkbox will be displayed and the values (Active or Inactive) will be displayed besides to it and it shouldn't be displayed. I just want the checkbox to be displayed.
So how to modify them?
ASP.NET code:
<%-- GridView for User Management Subsystem --%>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("IsActive")%>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
//for updating the (IsActive) column using checkbox inside the GridView
protected void isActive_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
//Get the ID which is the NetworkID of the employee
string username = gvrow.Cells[2].Text;
bool status = chkStatus.Checked;
string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string updateIsActive = "UPDATE Employee SET IsActive = #IsActive WHERE Username = #Username";
SqlCommand cmd = new SqlCommand(updateIsActive, conn);
cmd.Parameters.AddWithValue("#IsActive", status);
cmd.Parameters.AddWithValue("#Username", username);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (SqlException se)
{
throw se;
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
UPDATE:
I update my code as following:
ASP.NET Code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind:
//For showing Active or Inactive in the IsActive column instead of True or False
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Here we will select the IsActive column and modify its text
Label isActive = new Label();
isActive = (Label)e.Row.FindControl("lblIsActive");
//Now, after getting the reference, we can set its text
isActive.Text = "Active or Inactive";
// First check Checkedbox is check or not, if not make it grey
//if (e.Row.Cells[6].Text == "False")
// GridView1.BackColor = Color.Gray;
}
}
And I am getting the following error and I don't know why:
For question no: 1
You have to add an Row_DataBound Event of your grid view, in which you select the IsActive column and replaced its text by Active and InActive. But before going to code behind make a little change to you aspx code: In your item template instead of direct binding place a label control and bind it as I does in the below code:
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// here you will select the IsActive column and modify it's text
Label isActive=new Label();
isActive = (Label) e.row.FindControl("lblIsActive");
// after getting the reference set its text
isActive.Text="Active or InActive";
}
}
For question no 2:
Remove the condition form this
Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'
and replace it with
Eval("IsActive")
Now check boxes will be displayed.
Updated Answer:
You are receiving an object reference not found error, Please debug your site and check it why you are unable to get the exact reference. I saw you code and it looks that your code is fine.
To prove that my code is working,I created a gridview with a single column
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// and bind this grid view in the Page_Load of my Page
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
DataRow row = dt.NewRow();
row[0] = "Waqar Janjua";
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
}
// When I view this page in the browser it shows "Waqar Janjua"
// Now to update the columns text, I add the following code and it works.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = new Label();
l = (Label)e.Row.FindControl("Label1");
l.Text = "waqar";
}
}
}
// When I run this page now, it shows me "Waqar" not "Waqar Janjua" The code works for me.
It is returning "true" or "false" as it is expecting a boolean data type from IsActive. If you want to change that out put, I suspect you need to amend this conditionally on the ItemDataBound event of the grid.