I have a large dataset binding to a gridview that is inside of a 300px height restricted DIV tag. When I select a row and trigger the edit function the page reloads the data (as desired) into the gridview and takes me back to the top regardless of how far I may have scrolled down.
Is there a way ideally only using asp.net c# to focus on the row that is being edited. I don't mind if this involves the row being placed at the top of the grid while in edit mode if that is required.
Below is CountryGrid.aspx
<%# Page Language="C#" MasterPageFile="~/MasterPageSimple.master" AutoEventWireup="true"
CodeFile="CountryGrid.aspx.cs" EnableEventValidation="false" Inherits="CountryGrid"
Title="JFA Admin Portal - OP49 Country Update" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<center>
<div class="headlanding">
<asp:Label ID="lb_Welcome" runat="server" CssClass="labelLargeFont" Text="Label">OP49 - Country Update</asp:Label>
<br />
<br />
<br />
<asp:Label ID="Label4" runat="server" CssClass="labelLargeFont" >You are currently modifying: </asp:Label>
<asp:Label ID="Country" runat="server" CssClass="labelLargeFont" />
<br />
<asp:Label ID="Label1" runat="server" CssClass="labelLargeFont" >For </asp:Label>
<asp:Label ID="Season" runat="server" CssClass="labelLargeFont" />
<br />
<br />
</div>
<br />
<div style="text-align: center">
<asp:Label ID="Error_Dashboard" runat="server" Font-Size="Small" ForeColor="#FF3300"></asp:Label>
<asp:Label ID="ErrorAccess" runat="server" Font-Size="Small" ForeColor="#FF3300"></asp:Label>
</center>
</div>
<asp:Panel ID="Panel1" runat="server" Font-Size="Large" CssClass="Grid_Panel" GroupingText="OP49 - Update Grid" Font-Bold="true">
<center>
<div style="max-height: 550px; overflow: auto;">
<asp:GridView ID="CountryGridView" DataKeyNames="i_SK_Accom" runat="server" Postback="False"
AutoGenerateColumns="False" CssClass="mGrid" RowStyle-CssClass="normal" Width="95%"
OnRowEditing="CountryGridView_RowEditing"
OnRowCancelingEdit="CountryGridView_RowCancelingEdit"
OnRowUpdating="CountryGridView_RowUpdating" >
<Columns>
<asp:TemplateField HeaderText="Accom Code">
<ItemTemplate>
<asp:Label ID="lb_Accom_Code" runat="server" Text='<%# Bind("Accom_Code") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_Accom_Code" runat="server" Text='<%# Bind("Accom_Code") %>' />
</EditItemTemplate>
<HeaderStyle Width="80px" />
<ItemStyle Width="80px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Accom Name">
<ItemTemplate>
<asp:Label ID="lb_Accom_Name" runat="server" Text='<%# Bind("Accom_Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_Accom_Name" runat="server" Text='<%# Bind("Accom_Name") %>' />
</EditItemTemplate>
<HeaderStyle Width="200px" />
<ItemStyle Width="200px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="OP49 Required?">
<EditItemTemplate>
<asp:DropDownList ID="txt_OP49" runat="server" SelectedValue='<%# Bind("OP49_Required") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_OP49" runat="server" Text='<%# Bind("OP49_Required") %>' />
</ItemTemplate>
<HeaderStyle Width="100px" />
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Weekly">
<EditItemTemplate>
<asp:DropDownList ID="txt_Weekly" runat="server" SelectedValue='<%# Bind("Weekly") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_Weekly" runat="server" Text='<%# Bind("Weekly") %>' />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Daily">
<EditItemTemplate>
<asp:DropDownList ID="txt_Daily" runat="server" SelectedValue='<%# Bind("Daily") %>' CssClass="DropBoxYN">
<asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
<asp:ListItem Text="No" Value="N"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb_Daily" runat="server" Text='<%# Bind("Daily") %>' />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" >
<ItemTemplate>
<asp:ImageButton ID="bt_Edit" runat="server" CommandName="Edit" AlternateText="Edit" ImageUrl="~/Images/Edit.gif" CssClass="ImageButton" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="bt_Update" runat="server" CommandName="Update" AlternateText="Update" ImageUrl="~/Images/save.png" CssClass="ImageButton" />
<asp:ImageButton ID="bt_Cancel" runat="server" CommandName="Cancel" AlternateText="Cancel" ImageUrl="~/Images/cancel.png" CssClass="ImageButton" />
</EditItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle Width="60px" Wrap="False" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:ImageButton ID="Home" runat="server" ImageUrl="~/Images/home.png" CssClass="ImageButtonLarge" AlternateText="Home" ToolTip="Home" OnClick="Click_Home" />
</center>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
And the code behind page:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;
public partial class CountryGrid : System.Web.UI.Page
{
SnowballInterface conn = new SnowballInterface();
SnowballInterface CurSeason = new SnowballInterface();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
if (Request["i_FK_CountryID"] == null)
{
Response.Redirect("Default.aspx");
}
#region Get Accom Data
SqlCommand EditCOComm = new SqlCommand("IFACE_JFA_COUNTRY", conn.sbConn);
EditCOComm.CommandType = CommandType.StoredProcedure;
EditCOComm.Parameters.Add("#Statement", SqlDbType.Char).Value = "CountryDetails";
EditCOComm.Parameters.Add("#i_FK_CountryID", SqlDbType.Int).Value = Request["i_FK_CountryID"].Trim().ToString();
try
{
conn.sbConn.Open();
SqlDataReader EditCOReader;
EditCOReader = EditCOComm.ExecuteReader();
// Download default values
while (EditCOReader.Read())
{
Country.Text = Convert.ToString(EditCOReader["Country_Name"]).Trim();
Season.Text = Convert.ToString(EditCOReader["Season_Name"]).Trim();
}
EditCOReader.Close();
}
catch (Exception)
{
}
finally
{
conn.sbConn.Close();
}
#endregion
if (!IsPostBack)
{
BindCountryGrid();
}
}
protected void CountryGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
CountryGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindCountryGrid();
}
protected void CountryGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
CountryGridView.EditIndex = -1;
//Bind data to the GridView control.
BindCountryGrid();
}
protected void CountryGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label Textbox_Accom = (Label)CountryGridView.Rows[e.RowIndex].FindControl("lbl_Accom_Code");
Label Textbox_Accom_Name = (Label)CountryGridView.Rows[e.RowIndex].FindControl("lbl_Accom_Name");
DropDownList Textbox_OP49 = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_OP49");
DropDownList Textbox_Weekly = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_Weekly");
DropDownList Textbox_Daily = (DropDownList)CountryGridView.Rows[e.RowIndex].FindControl("txt_Daily");
SqlCommand commEditConsultant = new SqlCommand("IFACE_JFA_ACCOM", conn.sbConn);
commEditConsultant.CommandType = CommandType.StoredProcedure;
commEditConsultant.Parameters.Add("#Statement", SqlDbType.VarChar).Value = "AccomGridUpdate";
commEditConsultant.Parameters.Add("#Page", SqlDbType.VarChar).Value = "OP49";
commEditConsultant.Parameters.Add("#PC_Username", SqlDbType.VarChar).Value = HttpContext.Current.User.Identity.Name.ToUpper().ToString();
commEditConsultant.Parameters.Add("#Season_Name", SqlDbType.VarChar).Value = Season.Text;
commEditConsultant.Parameters.Add("#Accom_Code", SqlDbType.VarChar).Value = Textbox_Accom.Text;
commEditConsultant.Parameters.Add("#i_FK_SeasonID", SqlDbType.VarChar).Value = Request["i_FK_SeasonID"].Trim().ToString();
commEditConsultant.Parameters.Add("#OP49_Required", SqlDbType.VarChar).Value = Textbox_OP49.Text;
commEditConsultant.Parameters.Add("#Weekly", SqlDbType.VarChar).Value = Textbox_Weekly.Text;
commEditConsultant.Parameters.Add("#Daily", SqlDbType.VarChar).Value = Textbox_Daily.Text;
conn.sbConn.Open();
commEditConsultant.ExecuteNonQuery();
CountryGridView.EditIndex = -1;
Error_Dashboard.Text = Textbox_Accom.Text + " - " + Textbox_Accom_Name.Text + " Updated Successfully!";
conn.sbConn.Close();
BindCountryGrid();
}
private void BindCountryGrid()
{
SqlCommand CountryGridSelect = new SqlCommand("IFACE_JFA_ACCOM", conn.sbConn);
CountryGridSelect.CommandType = CommandType.StoredProcedure;
CountryGridSelect.Parameters.Add("#Statement", SqlDbType.VarChar).Value = "CountryGridSelect";
CountryGridSelect.Parameters.Add("#i_FK_CountryID", SqlDbType.VarChar).Value = Request["i_FK_CountryID"].Trim().ToString();
try
{
conn.sbConn.Open();
SqlDataReader CountryGridSelectReader;
CountryGridSelectReader = CountryGridSelect.ExecuteReader();
CountryGridView.DataSource = CountryGridSelectReader;
CountryGridView.DataBind();
CountryGridSelectReader.Close();
}
finally
{
conn.sbConn.Close();
}
}
protected void Click_Home(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?i_FK_SeasonID=" + Request["i_FK_SeasonID"].Trim().ToString());
}
}
You can set MaintanScrollPositionOnPostback to true in page directives on your aspx page.
<%# Page Language="C#" AutoEventWireup="true" MaintainScrollPositionOnPostback="true" CodeBehind="Gridview.aspx.cs" Inherits="TestWebsite.Gridview" %>
Related
I have recently been involved in a mini-project and am trying to use asp.net with SQL in it. The problem I am facing is that the insert function is not working although the edit and delete are working perfectly fine on the same page. This is the home2.aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home2.aspx.cs" Inherits="DBPROJECT.Home2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-image:url(img1.jpg)" >
<form id="form2" runat="server">
<asp:GridView ID="ab" runat="server" Font-Names="Arial"
HorizontalAlign="Center" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px"
CellPadding="4" AutoGenerateColumns="False"
OnRowEditing="ab_RowEditing" OnRowCancelingEdit="ab_RowCancelingEdit"
OnRowDeleting="ab_RowDeleting" OnRowUpdating="ab_RowUpdating"
EnableViewState="False" ><AlternatingRowStyle HorizontalAlign="Center" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField HeaderText="Registration Number" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="aa" runat="server" Text='<%# Bind("reg_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemNo" runat="server" Text='<%# Bind("reg_no") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name Of NGO" HeaderStyle-
HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="bb" runat="server" Text='<%# Bind("nname") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemName" runat="server" Text='<%# Bind("nname") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="cc" runat="server" Text='<%# Bind("address") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTotalUnits" runat="server" Text='<%# Bind("address") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="OwnerID" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:Label ID="dd" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblItemNoo" runat="server" Text='<%# Bind("owner_id") %>'>
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<EmptyDataRowStyle HorizontalAlign="Center" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle Font-Bold="True" BackColor="#990000" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:GridView>
<br />
<asp:Label runat="server" text="Enter the registration number" Font-Bold="True" ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A1" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the name of NGO " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A2" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the address " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A3" ></asp:TextBox>
<br />
<br />
<asp:Label runat="server" text="Enter the owner's ID " Font-Bold="True"
ForeColor="White" BackColor="Black"></asp:Label>
<asp:TextBox runat="server" ID="A4" ></asp:TextBox>
<br />
<br />
<div>
<asp:Button runat="server" Text="Insert" ID="Button1"OnClick="Button1_Click"
BackColor="White" Font-Bold="True" Font-Size="Large" ForeColor="Maroon"/>
</div>
</form>
</body>
</html>
This is the aspx.cs file
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using DBPROJECT.DAL;
namespace DBPROJECT
{
public partial class Home2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadGrid();
}
public void LoadGrid()
{
myDAL objMyDal = new myDAL();
ab.DataSource = objMyDal.SelectItem();
ab.DataBind();
}
protected void ab_RowEditing(object sender, GridViewEditEventArgs e)
{
ab.EditIndex = e.NewEditIndex;
LoadGrid();
}
protected void ab_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)ab.Rows[e.RowIndex];
Label a1 = (Label)ab.Rows[e.RowIndex].FindControl("aa");
TextBox a2 = (TextBox)ab.Rows[e.RowIndex].FindControl("bb");
TextBox a3 = (TextBox)ab.Rows[e.RowIndex].FindControl("cc");
Label a4 = (Label)ab.Rows[e.RowIndex].FindControl("dd");
int reg_no = Convert.ToInt32(a1.Text.ToString());
string nname = a2.Text.ToString();
string address = a3.Text.ToString();
int owner1 = Convert.ToInt32(a4.Text.ToString());
myDAL objMyDal = new myDAL();
objMyDal.UpdateItem(reg_no, nname, address);
// ======================================================
ab.EditIndex = -1;
LoadGrid();
}
protected void ab_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
myDAL objMyDal = new myDAL();
GridViewRow row = ab.Rows[e.RowIndex];
Label itemLabel = (Label)row.FindControl("lblItemNo");
int ItemID = Convert.ToInt32(itemLabel.Text.ToString());
int result = objMyDal.DeleteItem(ItemID);
if (result == -1)
{
ab.DataSource = objMyDal.SelectItem();
ab.DataBind();
}
else
{
string message = "No row deleted";
ClientScript.RegisterOnSubmitStatement(this.GetType(),"alert", message.ToString());
}
}
protected void ab_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ab.EditIndex = -1;
LoadGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable DT = new DataTable();
int aa= Convert.ToInt32(A1.Text.ToString());
string bb = A2.Text.ToString();
string cc = A3.Text.ToString();
int dd = Convert.ToInt32(A4.Text.ToString());
Response.Write("<script>alert('Insert failed');</script>");
myDAL objMyDal = new myDAL();
objMyDal.insertItem(aa,bb,cc,dd,ref DT);
LoadGrid();
}
}
}
The definition in the dal file is as follows
public int insertItem(int reg, string name, string add, int o1, ref DataTable DT)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd,cmd1;
int result = 0;
try
{
//cmd1 = new SqlCommand("newNGO", con);
cmd = new SqlCommand("insert into NGO values (#reg_no,#nname,#address,#owner_id)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#reg_no", SqlDbType.Int).Value = reg;
cmd.Parameters.Add("#nname", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = add;
cmd.Parameters.Add("#owner_id", SqlDbType.Int).Value = o1;
/*
cmd1.Parameters.Add("#nname", SqlDbType.VarChar).Value = name;
cmd1.Parameters.Add("#address", SqlDbType.VarChar).Value = add;
cmd1.Parameters.Add("#owner_id", SqlDbType.Int).Value = o1;
*/
result = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
}
finally
{
con.Close();
}
return result;
}
The column names of the table are reg_no (int), nname(varchar), address(varchar) and owner_id(int). reg_no is the primary key and owner_id is foreign key.
I have been trying to find out the error since last week. Clicking the insert button does not throw any exception or error but it also does not insert the values in the database.
change cmd.Parameters.Add to cmd.Parameters.AddWithValue and then try
I think I have figured it out. The variable nname was set as varchar(20) and I was entering a string "Doctors without Borders" which is clearly larger than 20 and therefore it was throwing the exception. Thanks for your help and concerns.
I am using ASP.NET and Entity Framework and Tab control of AJAX
I have a dropdown list control in gridview which is in TAB control Am not able to bind dropdown list control.
Tab Control --> Gridview --> Dropdown list
My ASP.NET Code is
<ajax:TabContainer ID="TabContainer2" runat="server" CssClass="fancy fancy-green">
<ajax:TabPanel ID="TabPanel1" runat="server">
<HeaderTemplate>
College Toppers
</HeaderTemplate>
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server">
<div>
<asp:GridView ID="GridView1" DataKeyNames="TL_ID" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" ShowFooter="True" OnRowDataBound="GRVToppers_RowDataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Admin/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" /><asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Admin/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Admin/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Admin/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" /><asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server" ImageUrl="~/Admin/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Topper List No">
<EditItemTemplate>
<asp:Label ID="lblEditTpid" runat="server" Text='<%#Eval("TL_ID") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblShowTpid" runat="server" Text='<%#Eval("TL_ID") %>' />
</ItemTemplate>
<ControlStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Department Name">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditDeptname" runat="server" Width="90" DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="true"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddladdnewDeptname" runat="server" Width="90" DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="True"></asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblShowDeptname" runat="server" Text='<%#Eval("DEPT_NAME") %>' Width="90" />
</ItemTemplate>
<ControlStyle Width="30px" />
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
</asp:Panel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
==================
My C# code is
protected void GRVToppers_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
var dept = from n in ecme.DEPT_MASTER
select new { n.DEPT_ID, n.DEPT_NAME };
DropDownList ddl = null;
if (e.Row.RowType == DataControlRowType.Footer)
{
ddl = e.Row.FindControl("ddladdnewDeptname") as DropDownList;
int cnt = 0;
cnt = dept.Count();
ListItem[] items = new ListItem[cnt];
for (int i = 0; i < cnt; i++)
{
items[i] = new ListItem("DEPT_NAME", "DEPT_ID");
}
}
}
catch (Exception)
{ }
}
========================
You can do this very easily...
Remove
DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="True"
and
DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="true"
from aspx code
and Make changes in
protected void GRVToppers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var dept = from n in ecme.DEPT_MASTER
select new { n.DEPT_ID, n.DEPT_NAME };
DropDownList ddl = (DropDownList)e.Row.FindControl("ddladdnewDeptname");
ddl.DataTextField = "DEPT_NAME";
ddl.DataValueField = "DEPT_ID";
ddl.DataSource = dept.ToList();
ddl.DataBind();
ddl.Items.Insert(0, "--Select Department--");
}
}
100% sure this 'll work...
I have a problem to update a datagridview when modifications are made.
To update a column ("Criticite"), I implemented a DropDownList containing 2 choices. I can select a choice, but I click on the "Update" button none change is done.
Could you please help me on this subject ?
Thanks a lot !
Here is the C# code :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.IO.Compression;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "select ID,Client,Entite,Date,Source,Domaine,Categorie,SousCategorie,Criticite,Contenu from Results";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("DropDownList1");
String query = "Select Criticite from Results";
SqlCommand cmd = new SqlCommand(query);
DataTable dt = GetData(cmd);
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "Criticite";
drpcategory1.DataValueField = "Criticite";
drpcategory1.DataBind();
}
}
private void BindData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + ";select ID,Client,Entite,Date,Source,Domaine,Categorie,SousCategorie,Criticite,Contenu from Results", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label ID = GridView1.Rows[e.RowIndex].FindControl("ID") as Label;
TextBox Entite = GridView1.Rows[e.RowIndex].FindControl("txtEntite") as TextBox;
TextBox Date = GridView1.Rows[e.RowIndex].FindControl("txtDate") as TextBox;
TextBox Source = GridView1.Rows[e.RowIndex].FindControl("txtSource") as TextBox;
TextBox Domaine = GridView1.Rows[e.RowIndex].FindControl("txtDomaine") as TextBox;
TextBox Categorie = GridView1.Rows[e.RowIndex].FindControl("txtCategorie") as TextBox;
TextBox SousCategorie = GridView1.Rows[e.RowIndex].FindControl("txtSousCategorie") as TextBox;
TextBox Criticite = GridView1.Rows[e.RowIndex].FindControl("lblCriticite") as TextBox;
TextBox Contenu = GridView1.Rows[e.RowIndex].FindControl("txtContenu") as TextBox;
String UpdateQuery = string.Format("UPDATE Results SET Entite='{0}',Date='{1}',Source='{2}',Domaine='{3}',Categorie='{4}',SousCategorie='{5}',Criticite='{6}',Contenu='{7}' WHERE ID = {8}", Entite.Text, Date.Text, Source.Text, Domaine.Text, Categorie.Text, SousCategorie.Text, Criticite.Text, Contenu.Text, ID.Text);
GridView1.EditIndex = -1;
BindData(UpdateQuery);
}
}
And here the aspx default page :
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<p>
Début</p>
<p>
</p>
<p>
</p>
<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red"
OnRowEditing = "EditCustomer"
OnRowDataBound = "RowDataBound"
OnRowUpdating = "RowUpdating"
OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:TemplateField Visible="false" HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="ID" Text='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client">
<ItemTemplate>
<asp:Label runat="server" ID="Client" Text='<%#Eval("Client") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtClient" Text='<%#Eval("Client") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Entite">
<ItemTemplate>
<asp:Label runat="server" ID="Entite" Text='<%#Eval("Entite") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtEntite" Text='<%#Eval("Entite") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label runat="server" ID="Date" Text='<%#Eval("Date") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtDate" Text='<%#Eval("Date") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Source">
<ItemTemplate>
<asp:Label runat="server" ID="Source" Text='<%#Eval("Source") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSource" Text='<%#Eval("Source") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Domaine">
<ItemTemplate>
<asp:Label runat="server" ID="Domaine" Text='<%#Eval("Domaine") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtDomaine" Text='<%#Eval("Domaine") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Categorie">
<ItemTemplate>
<asp:Label runat="server" ID="Categorie" Text='<%#Eval("Categorie") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtCategorie" Text='<%#Eval("Categorie") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SousCategorie">
<ItemTemplate>
<asp:Label runat="server" ID="SousCategorie" Text='<%#Eval("SousCategorie") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSousCategorie" Text='<%#Eval("SousCategorie") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Criticite">
<ItemTemplate>
<asp:Label runat="server" ID="lblCriticite" Text='<%#Eval("Criticite") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="lblCriticite" Text='<%#Eval("Criticite") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList1" runat = "server"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contenu">
<ItemTemplate>
<asp:Label runat="server" ID="Contenu" Text='<%#Eval("Contenu") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtContenu" Text='<%#Eval("Contenu") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
Change the following line
TextBox Criticite = GridView1.Rows[e.RowIndex].FindControl("lblCriticite") as TextBox;
into:
DropDownList Criticite = GridView1.Rows[e.RowIndex].FindControl("DropDownList1") as DropDownList;
and use Criticite.SelectedValue instead of Criticite.Text.
Also, your update query is at risk of SQL injection attacks.
How to Store SelectedRow.Cell[0] value in a session when CommandField is "Select" in a GridView. ? What the changes i will do in my code so that when a Select Command executes on my grid (By Clicking on Select Link of my grid), It will Store the NatureOfWorkID of that row in the session variable. Below is my code. Please guide me that what changes required in the below code so that when ever some one will click on Select, the natureofworkID of that row will be stored in a Session and i will bind another grid from the session variable as per my requirement.
<asp:GridView ID="GVNatureOFWork" runat="server" AllowPaging="true" ShowFooter="true" PageSize="10" AutoGenerateColumns="false"
DataKeyNames="NatureOfWorkID"
OnPageIndexChanging="GVNatureOFWork_PageIndexChanging"
onrowcancelingedit="GVNatureOFWork_RowCancelingEdit"
onrowcommand="GVNatureOFWork_RowCommand" onrowdeleting="GVNatureOFWork_RowDeleting"
onrowediting="GVNatureOFWork_RowEditing" onrowupdating="GVNatureOFWork_RowUpdating"
OnSelectedIndexChanged="GVNatureOFWork_SelectedIndexChanged" OnRowDataBound="GVNatureOFWork_RowDataBound"
HeaderStyle-BackColor="BlueViolet"
HeaderStyle-ForeColor="White" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="NatureOfWorkID">
<ItemTemplate>
<asp:Label ID="lblNautureOfWorkID" runat="server" Text='<%#Eval("NatureOfWorkID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nature of Work Name">
<ItemTemplate>
<asp:Label ID="lblNatureOfWorkName" runat="server" Text='<%#Eval("NatureOfWorkName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNatureOfWorkName" runat="server" Text='<%#Eval("NatureOfWorkName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddNatureOfWorkName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enable/Disable">
<ItemTemplate>
<asp:Label ID="lblNOWStatus" runat="server" Text='<%# (int)Eval("IsNOWEnabled") == 1 ? "Enabled" : "Disabled" %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="radiolistStatus" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="radiolistStatusAdd" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField ShowSelectButton="True" ItemStyle-CssClass="HiddenColumn" HeaderStyle-CssClass="HiddenColumn"/>
</Columns>
</asp:GridView><br /><br /><br /><br />
<asp:GridView ID="GVRegionProject" runat="server" AllowPaging="true" ShowFooter="true" PageSize="10" AutoGenerateColumns="false"
OnPageIndexChanging="GVRegionProject_PageIndexChanging"
onrowcancelingedit="GVRegionProject_RowCancelingEdit"
onrowcommand="GVRegionProject_RowCommand" onrowdeleting="GVRegionProject_RowDeleting"
onrowediting="GVRegionProject_RowEditing" onrowupdating="GVRegionProject_RowUpdating"
OnSelectedIndexChanged="GVRegionProject_SelectedIndexChanged"
HeaderStyle-BackColor="BlueViolet"
HeaderStyle-ForeColor="White" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="Region/Project ID">
<ItemTemplate>
<asp:Label ID="lblRegionProjectID" runat="server" Text='<%#Eval("RegionProjectID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Region/Project Name">
<ItemTemplate>
<asp:Label ID="lblRegionProjectName" runat="server" Text='<%#Eval("RegionProjectName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRegionProjectName" runat="server" Text='<%#Eval("RegionProjectName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddRegionProjectName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enable/Disable">
<ItemTemplate>
<asp:Label ID="lblRPStatus" runat="server" Text='<%# (int)Eval("IsRegionProjectEnabled") == 1 ? "Enabled" : "Disabled" %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="radiolistStatus" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="radiolistStatusAdd" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="County" ShowHeader="false" ShowSelectButton="True"/>
</Columns>
</asp:GridView>
Code Behind is :-
private void BindGrid()
{
dataTable = new DataTable();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM natureOfWork";
ad = new SqlDataAdapter(cmd);
ad.Fill(dataTable);
GVNatureOFWork.DataSource = dataTable;
GVNatureOFWork.DataBind();
}
protected void GVNatureOFWork_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GVNatureOFWork.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void GVNatureOFWork_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GVNatureOFWork.EditIndex = -1;
BindGrid();
}
protected void GVNatureOFWork_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtAddNatureOfWorkName = (TextBox)GVNatureOFWork.FooterRow.FindControl("txtAddNatureOfWorkName");
RadioButtonList radiolistStatusAdd = (RadioButtonList)GVNatureOFWork.FooterRow.FindControl("radiolistStatusAdd");
if ((txtAddNatureOfWorkName.Text != "")&&(radiolistStatusAdd.SelectedValue != string.Empty))
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO NatureOFWork(NatureOFWorkname, isNOWEnabled ) Values('" + txtAddNatureOfWorkName.Text + "', '" + radiolistStatusAdd.SelectedValue.ToString() + "')";
conn.Open();
cmd.ExecuteNonQuery();
}
BindGrid();
conn.Close();
}
if (e.CommandName.Equals("Select"))
{
}
}
protected void GVNatureOFWork_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.Rows[e.RowIndex].FindControl("lblNautureOfWorkID");
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM NatureOFWork WHERE NatureOfWorkID='" + lblNautureOfWorkID.Text.ToString() + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindGrid();
}
protected void GVNatureOFWork_RowEditing(object sender, GridViewEditEventArgs e)
{
GVNatureOFWork.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GVNatureOFWork_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.Rows[e.RowIndex].FindControl("lblNautureOfWorkID");
TextBox txtNatureOfWorkName = (TextBox)GVNatureOFWork.Rows[e.RowIndex].FindControl("txtNatureOfWorkName");
RadioButtonList radiolistStatus = (RadioButtonList)GVNatureOFWork.Rows[e.RowIndex].FindControl("radiolistStatus");
string isenabled = radiolistStatus.SelectedValue.ToString();
cmd.Connection = conn;
cmd.CommandText = "UPDATE NatureOfWork SET NatureOfWorkname ='" + txtNatureOfWorkName.Text + "',IsNowEnabled=" + isenabled.ToString() + " WHERE NatureOFWorkID=" + lblNautureOfWorkID.Text.ToString();
conn.Open();
cmd.ExecuteNonQuery();
GVNatureOFWork.EditIndex = -1;
BindGrid();
conn.Close();
}
protected void GVNatureOFWork_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblNautureOfWorkID = (Label)e.Row.FindControl("lblNautureOfWorkID");
Label lblNatureOfWorkName = (Label)e.Row.FindControl("lblNatureOfWorkName");
TextBox txtNatureOfWorkName = (TextBox)e.Row.FindControl("txtNatureOfWorkName");
TextBox txtAddNatureOfWorkName = (TextBox)e.Row.FindControl("txtAddNatureOfWorkName");
RadioButtonList radiolistStatusAdd = (RadioButtonList)e.Row.FindControl("radiolistStatusAdd");
RadioButtonList radiolistStatus = (RadioButtonList)e.Row.FindControl("radiolistStatus");
Label lblNOWStatus = (Label)e.Row.FindControl("lblNOWStatus");
}
if (e.Row.RowType == DataControlRowType.Footer)
{
}
}
protected void GVNatureOFWork_SelectedIndexChanged(object sender, EventArgs e)
{
string natureOfWorkID=GVNatureOFWork.SelectedRow.Cells[0].Text;
BindRegionProjectInfoGrid();
}
Your code editted :
(e.CommandName.Equals("Select"))
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.SelectedRow.FindControl("lblNautureOfWorkID");
if(lblNautureOfWorkID != null)
{
string natureofworkID = lblNautureOfWorkID.Text.ToString();
}
}
protected void GVNatureOFWork_SelectedIndexChanged(object sender, EventArgs e)
{
int index = GVNatureOFWork.SelectedIndex;
string natureofwrkid = GVNatureOFWork.DataKeys[index].Value.ToString();
Session["NOWID"] = natureofwrkid;
lblDisplayNOWID.Text = natureofwrkid;
BindRegionProjectInfoGrid();
}
By adding these lines, Now i am able to get Cell[0] value of the selected row in my grid. Thanks To every one for guiding me to get the solution.
I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}