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.
Related
I have a gridview with checkboxes to select the row. On checking the checkbox I need to get the row values into a string/session. Below is the code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_OnRowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width ="1000px" class="grid" AllowPaging="True" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last" PageButtonCount="2" PagerSettings-Mode="NumericFirstLast" PageSize="5">
<PagerSettings Mode="NumericFirstLast" PageButtonCount="2" FirstPageText="First" LastPageText="Last"/>
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Connection">
<ItemTemplate>
<asp:Label ID="lbl_conn" runat="server" Text='<%#Eval("Connection") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID">
<ItemTemplate>
<asp:Label ID="lbl_Usrid" runat="server" Text='<%#Eval("UserID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Usrid" runat="server" Text='<%#Eval("UserID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:Label ID="lbl_pwd" runat="server" Text='<%#Eval("Password") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_pwd" runat="server" Text='<%#Eval("Password") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Connection Name">
<ItemTemplate>
<asp:Label ID="lbl_conName" runat="server" Text='<%#Eval("Connection_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_conName" runat="server" Text='<%#Eval("Connection_Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text=" Edit" class=" btnEdit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" class=" btnEdit" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" class=" btnEdit" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btn_Delete" runat="server" class=" btnDelete" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this event?')" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
There is a button below the grid. on click of the button I need to get the values.
protected void LinkButton1_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in GdvTestData.Rows)
{
CheckBox chk = (item.FindControl("CheckBox3") as CheckBox);
if (chk.Checked)
{
string conn = item.Cells[1].Text;
}
}
}
But am getting null value for string conn = item.Cells[1].Text;
where am I going wrong
Grid contains the different row type like header row , data row and footer row. You need to get content from the data row only then please check the row type first if it is a data row then try to get cell values. GridViewRow.RowType Property
foreach(GridViewRow item in GdvTestData.Rows) {
// check row is datarow
if (item.RowType == DataControlRowType.DataRow) {
CheckBox chk = (item.FindControl("CheckBox3") as CheckBox);
if (chk.Checked)
{
Label MyLabel = (Label)item.FindControl("lbl_conn");
string conn = MyLabel.Text;
}
}
}
I am extracting data from database in gridview, where I have given a link button "Edit" for editing the data of that row. However while editing , one of the columns(YEAR) of my gridview becomes a dropdown list. While fetching the data from database, the Column "Year" consists of label and in edit mode it gets changed to dropdownlist. Moreover I added a condition to make the link buttons appear/disappear based on the value of the Label "Year". When I edit the particular row it throws an error because as soon as edit command is called it converts the column into dropdownlist however the row_databound searches for label. It shows "Object not set to an instance....." PLease help
Aspx
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSource2" OnRowDataBound="gv1_RowDataBound" OnRowUpdating="gv1_RowUpdating" DataKeyNames="tid" CssClass="auto-style1" Width="694px">
<Columns>
<asp:TemplateField HeaderText="Sr No">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="tid" SortExpression="tid" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("tid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<EditItemTemplate>
<asp:TextBox ID="txtTitle1" runat="server" Text='<%# Bind("title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Bind("title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Category" SortExpression="category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server" Text='<%# Bind("category") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="rbtnlist" runat="server"><asp:ListItem Text="Soft Skills"></asp:ListItem><asp:ListItem Text="Technical Skills"></asp:ListItem></asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Announced at" SortExpression="dt">
<ItemTemplate>
<asp:Label ID="lblDt" runat="server" Text='<%# Bind("dt", "{0:dd/MMM/yyyy HH:mm tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year" SortExpression="year">
<EditItemTemplate>
<asp:DropDownList ID="ddlyr" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblyr" runat="server" Text='<%# Bind("year") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id" SortExpression="userid">
<ItemTemplate>
<asp:Label ID="lblUid" runat="server" Text='<%# Bind("userid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btndel" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return isConfirm()" Visible="false"></asp:LinkButton>
<%--<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="btnupdte" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncncl" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle ForeColor="#003399" HorizontalAlign="Left" BackColor="#99CCCC" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
c#
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbly = (Label)e.Row.FindControl("lblyr");
if (lbly.Text == DateTime.Now.Year.ToString() || lbly.Text == ((DateTime.Now.Year)-1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0) {
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year)-1) ; i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}
}
I am assuming that you are binding your grid with a DataTable with colum name "Year". Try below code where dt refers to your Datatable:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowno = e.Row.DataItemIndex;
//Suppose dt is DataTable to which you are binding your grid
//and year is the column name within this datatable
string year = Convert.ToString(dt.Rows[e.Row.DataItemIndex]["year"]);
if (year == DateTime.Now.Year.ToString() || year == ((DateTime.Now.Year) - 1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year) - 1); i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}
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 populated with elements extracted from a table in the database. Each row contains 2 textboxes and 1 drop down list. The drop down list is filled when the page is loaded.
My issue is: when I edit the row, select another item from the drop down list and then click on update button, nothing changes. The drop down list still returns to its default value, neither the modiefied values are updated in the db (delete doesn't work etc). I can't understand the reason. Please help me.
My Gridview:
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView_OnRowDataBound" OnRowUpdating="GridView_OnRowUpdating"
DataKeyNames="id" DataSourceID="DataSource" ><AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowCancelButton="True" />
<asp:TemplateField HeaderText="currentCity" SortExpression="currentCity" ItemStyle- HorizontalAlign="Center" Visible="false">
<ItemTemplate>
<asp:Label runat="server" ID="lblcurrentCity" Text='<%# Bind("CodiceContrattoRisorsa") %>' Visible="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id" SortExpression="id" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txtId" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name" ItemStyle- HorizontalAlign="Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txtName" Text='<%# Bind("name") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="city" SortExpression="city" ItemStyle- HorizontalAlign="Center">
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Enabled="false" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:EntityDataSource ID="DataSource"
runat="server" ContextTypeName="Context"
EntitySetName="users" EntityTypeFilter="user"
EnableDelete="True" EnableUpdate="True" />
Loading page....
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyGridView.DataBind();
}
protected void GridViewCausali_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// initialize ddl in gridview
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCity");
List<city> cities = new List<city>();
cities = GetFromDB();
ddl.DataSource = cities;
ddl.DataBind();
ddl.Items.FindByValue((e.Row.FindControl("lblcurrentCity") as
Label).Text).Selected = true;
}
}
protected void GridView_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl = (DropDownList)MyGridView.Rows[e.RowIndex].FindControl("ddlCity");
string test = ddl.SelectedValue;
Label lbl = (Label)MyGridView.Rows[e.RowIndex].FindControl("lblcurrentCity");
lbl.Text = ddl.SelectedValue;
ddl.Items.FindByValue((MyGridView.Rows[e.RowIndex].FindControl("lblcurrentCity") as Label).Text).Selected = true;
}
I suggest you to add DefaultContainerName property, add stringconnection
<asp:EntityDataSource ID="DataSource" runat="server"
ConnectionString="name=..."
DefaultContainerName="..."
EntitySetName="users"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"/>
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 only one problem which is the following: when the checkbox is unchecked that means the employee is inactive, so I want the row that shows his information to be in a grey color (like disabled).
So how to do that?
ASP.NET code:
<%-- GridView for User Management Subsystem --%>
<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 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();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// First check Checkedbox is check or not, In Cells insert you IsActive column index
if( e.Row.Cells[1].Text == "False" )
GridView1.BackColor = Color.Gray;
}
}
in your method on unchecked status of the checkbox you will have set the BackColor of the GrdiViewRow like this gvrow.BackColor= Color.Gray;
One important think is on the first load you will need to repeat similar logic of the GridView's OnRowDataBound so move it in method and reuse
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;
if(!status)//this is checkbox is unchecked then set backcolor to Gray
{
gvrow .BackColor = Color.Gray;
}
.......