GridView_RowUpdating not firing - c#

I have Gridview with ItemTemplate and EditItemTemplate:
But when i click "Ok" button, nothing happens. I tried to put trace point on RowUpdating event and click "Ok" button, but its not even triggered. I assume, that problem could be in the same "Id" of ItemTemplate and EditItemTemplate lbl_first_fl. But earlier this worked fine, the only thing was changed - i updated Visual studio to 2015 and changed Windows to 8. So i installed VS 2013, but problem still occures. Any suggestions? Or maybe how can i deal with it using different id's?
aspx page:
<asp:GridView ID="GridView5" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" Height="430px" OnRowCancelingEdit="GridView5_RowCancelingEdit" OnRowDataBound="GridView5_RowDataBound" OnRowEditing="GridView5_RowEditing" OnRowUpdating="GridView5_RowUpdating" Width="100%" CssClass="gridview" GridLines="none">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-Width="100">
<EditItemTemplate>
<asp:Button ID="btn_Update_fl" runat="server" CommandName="Update" Text="Ок" />
<asp:Button ID="btn_Cancel_fl" runat="server" CommandName="Cancel" Text="Отмена" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btn_Edit_fl" runat="server" CommandName="Edit" Text="✎" Enabled='<%# Flag %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="08:00 - 17:00" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="true"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_first_fl" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField/>
</Columns>
</asp:GridView>
OnRowUpdating event:
protected void GridView5_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
DropDownList First_fl = GridView5.Rows[e.RowIndex].FindControl("ddl_first_fl") as DropDownList;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd_fl = new SqlCommand("Update [Duty].[dbo].[Schedule_FirstLine] set First='" + First_fl.Text + "', con);
cmd_fl.ExecuteNonQuery();
con.Close();
GridView5.EditIndex = -1;
ShowDataFirstLine();
}
Binding Gridview:
protected void ShowDataFirstLine()
{
DateTime date = Convert.ToDateTime(Calendar1.VisibleDate.Date.ToString());
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
string GridDS_FirstLine = "set dateformat dmy Select DutyDate,WeekDay,First, Second from [Duty].[dbo].[Schedule_FirstLine] WHERE DutyDate >= '" + firstDayOfMonth + "' AND DutyDate <= '" + lastDayOfMonth + "'";
dt_FirstLine = new DataTable();
con_FirstLine = new SqlConnection(cs);
con_FirstLine.Open();
adapt_FirstLine = new SqlDataAdapter(GridDS_FirstLine, con_FirstLine);
adapt_FirstLine.Fill(dt_FirstLine);
if (dt_FirstLine.Rows.Count > 0)
{
GridView5.DataSource = dt_FirstLine;
GridView5.DataBind();
}
GridView5.Columns[0].Visible = true;
}

You name the event on the grid like this?
<asp:GridView ID="TaskGridView" runat="server"
AutoGenerateEditButton="True"
AllowPaging="true"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating"
OnPageIndexChanging="TaskGridView_PageIndexChanging">
</asp:GridView>

Related

grid view does not show data from database once bind

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

Issues with dropdown causing error: Object reference not set to an instance of an object

I have drop down box that does not keep the selected value so i had to add this line of code:
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
But adding this line of code is causing me another problem. I have built the dropdown in a Gridview and the Gridview has an Edit link, once you click the edit then you should see the drop down box, but the issue now is when i click the Edit link and nothing has been selected in the dropdown then i get an error. It only works when something was already selected. Here is my code:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
int current_quest_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
DropDownList ddl_Answer = (DropDownList)e.Row.FindControl("ddl_Answer");
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from MainTable D, SecondryTable Q where Q.ANS_OPT = D.ID and QUEST_SK= '" + current_quest_sk + "' ");
cmd1.Connection = con2;
con2.Open();
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
con2.Close();
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
}
here is the markup for the dropdown
<asp:GridView ID="GridView1" runat="server" Width="870px" OnRowDataBound="RowDataBound"
AutoGenerateColumns="False" Font-Names="Arial" Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
HeaderStyle-BackColor="green" AllowPaging="True" ShowFooter="True" OnPageIndexChanging="OnPaging"
OnRowEditing="EditGridView1" OnRowUpdating="UpdateGridView1" OnRowCancelingEdit="CancelEdit"
CellPadding="4" BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px"
DataKeyNames="QUEST_SK">
<AlternatingRowStyle BackColor="#C2D69B" />
<Columns>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" >
<ItemStyle Font-Size="Smaller" ForeColor="#FF3300" />
</asp:CommandField>
</Columns>

Selecting a Datevalue from GridView Cell and Use it as Parameter to a SQL Query

Hi I am Presently running an ASP.NET application
Now problem is with the Next button in the app, whenever someone clicks it, it returns the data of date range SYSDATE + 18 to SYDATE + 36 . But the way it should work is .. it should take the first date value from the GridView Date Cell and Returns the data for GridViewFirstCellDate+18 to GridViewFirstCellDate+36. My Gridview code is al follows. Eg the date in Image is Tuesday,November 19,2013 , so clicking Next button should retrun from 7/12/2013 and 25/12/2013 's data (DD/MM/YYYY)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" EnableModelValidation="True" GridLines="Horizontal"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText = "Date">
<ItemTemplate>
<asp:Label ID="Date" Runat="Server"
Text='<%# Eval("DUTY_DATE", "{0:dddd,MMMM dd,yyyy}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Role">
<ItemTemplate>
<asp:Label ID="Role" Runat="Server"
Text='<%# Eval("DUTY_DESC") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("FULLNAME") %>' NavigateUrl='<%# Eval("ROW_PASS", "/sites/HQDO/Pages/OfficerDetails.aspx?_ID={0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("MOBILE_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("OFFICE_TEL") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:GridView>
and the CodeBehind for next button is below
protected void Button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "SELECT CONTACTS.ROWID as ROW_PASS,DUTY_ROTA.DUTY_DATE AS DUTY_DATE,DUTY_ROTA.DUTY_TYPE AS DUTY_TYPE,DUTY_ROTA.DUTY_OFFICER AS DUTY_OFFICER,DUTY_TYPES.DESCRIPTION AS DUTY_DESC,CONTACTS.SNAME AS FULLNAME,CONTACTS.MOBILE AS MOBILE_NO,CONTACTS.OFFICETEL AS OFFICE_TEL FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE+18 and SYSDATE+36 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
}
I tried to catch the value in below way
LabelDate.Text = GridView1.Rows[0].Cells[0].Text;
And then convert it to Date and use it in my SQL. But the LabelDate.Text is unable to store the data not sure why.
Can you buddies please help How could I Capture GridView First Row First Cells data and Add 18 days to it...also I want to use it in my SQL.
You need to add a handler for GridView.RowDataBound
Here's a quick example:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LabelDate.Text = e.Row.Cells[0].Text;
}
Try :
LabelDate.Text = Convert.ToDateTime(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
LabelDate.Text = DateTime.Parse(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("fr-FR");
Label1.Text = DateTime.ParseExact(GridView1.Rows[0].Cells[3].Text, "g", provider).AddDays(18).ToShortDateString();

Update Selected Row in Gridview

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

How to modify this checkbox inside the GridView?

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.

Categories

Resources