I check many sites and referred many codes before I could post a questions here. I am facing lot of confusions seeing them. Here is my problem.
I have a GridView and I have bound it from code behind as :
public void BindData()
{
SqlCommand comd = new SqlCommand("SELECT * FROM " + Label2.Text + "", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
And my asp.net for the same looks like :
<asp:GridView ID="GridView1" runat="server" ForeColor="#333333"
AutoGenerateEditButton="True" DataKeyNames="Locations"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdatabound="GridView1_RowDataBound"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Locations">
<ItemTemplate>
<asp:Label ID="LblLocations" runat="server" Text='<%#Eval("Locations") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lamp_Profile1">
<ItemTemplate>
<asp:Label ID="LblLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditLamp_Profile1" runat="server" Text='<%#Eval("Lamp_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fan_Profile1">
<ItemTemplate>
<asp:Label ID="LblFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditFan_Profile1" runat="server" Text='<%#Eval("Fan_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AC_Profile1">
<ItemTemplate>
<asp:Label ID="LblAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblEditAC_Profile1" runat="server" Text='<%#Eval("AC_Profile1") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
And I have written my GridView1_RowCancelingEdit like:
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
And my GridView1_RowEditing looks like:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
And my GridView1_RowUpdating looks like:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = e.RowIndex;
Label Locations = GridView1.Rows[e.RowIndex].FindControl("LblLocations") as Label;
//ViewState["Locations_Instance"] = Locations.Text;
Label Lamp_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblLamp_Profile1") as Label;
Label Fan_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblFan_Profile1") as Label;
Label AC_Profile1 = GridView1.Rows[e.RowIndex].FindControl("LblAC_Profile1") as Label;
string query = "UPDATE " + Label3.Text + " SET Lamp_Profile1 ='" + Lamp_Profile1 + "', Fan_Profile1 ='" + Fan_Profile1 + "', AC_Profile1 ='" + AC_Profile1 + "' WHERE Locations = '" + Locations + "'";
com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
//lbldisplay.Text = "Updated Successfully";
}
From this I am getting what ever row I am binding using template field as well as database columns in my GridView and Once I click on Edit in the GridView, the whole GridView disappears.
Please help me.
You can find the textbox that is generated on edit event in the RowUpdating event below and assign it to a string variable.
Then have a seperate function to update the values entered and finally call your BindGrid() function which again binds the gridview..
Note: I'm using stored procedure to update my DB table.
protected void grdKeywords_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grdKeywords.Rows[e.RowIndex];
TextBox txtKeyword = row.FindControl("txtGridKeyword") as TextBox;
string keyword = string.Empty;
keyword = txtKeyword.Text;
UpdateKeyword(keyword.ToLower());
}
public int UpdateKeyword(string strKeyword)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
SqlCommand cmdUpdateKeyword = BuildCommand(conn, "proc_UpdateKeyword");
cmdUpdateKeyword.Parameters.AddWithValue("#Keyword", strKeyword);
conn.Open();
int i = Convert.ToInt32(cmdUpdateKeyword.ExecuteScalar());
conn.Close();
BindGrid();
}
To manually specify columns for the gridview you have to set AutoGenerateColumns="false". Now you can specify the columns that you want in your GridView. You can use both "BoundFields" & "TemplateFields" now. As shown below.
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="column1" HeaderText="Column1" SortExpression="" />
<asp:BoundField DataField="column2" HeaderText="Column2" SortExpression="" />
<asp:TemplateField SortExpression="points">
<HeaderTemplate>HELLO</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("hello") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now you can use:
GridView.RowDataBound Event to bind data to the data row.
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label Label1= ((Label)e.Row.FindControl("Label1"));
Label1.Text = "YOURDATA";
}
}
if you call BindData in page load then do that:
if (!IsPostBack)
BindData();
That might solve your problem...
Cheers
public int UpdateKeyword(string strKeyword)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
SqlCommand cmdUpdateKeyword = BuildCommand(conn, "proc_UpdateKeyword");
cmdUpdateKeyword.Parameters.AddWithValue("#Keyword", strKeyword);
conn.Open();
int i = Convert.ToInt32(cmdUpdateKeyword.ExecuteScalar());
conn.Close();
BindGrid();
}
Make sure you have EnableViewState="true" set in your GridView. It solved disapperance-issue in my case.
try this ..
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = e.RowIndex;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox PrStyle = (TextBox)row.FindControl("PrStyle");
TextBox PrID = (TextBox)row.FindControl("PrID");
GridView1.EditIndex = -1;
SqlCommand cmd = new SqlCommand("Update dt Set PrStyle='" + PrStyle + "',PrID='" + PrID + "'");
}
Related
I need some assistance with downloading a file in a specific row in my GridView.
This is my code for the the GridView markup:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="id"
CssClass="mydatagrid"
Width="550px"
BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None"
BorderWidth="1px"
CellPadding="3"
CellSpacing="2"
AllowSorting="true">
<Columns>
<asp:BoundField DataField="filename" HeaderText="Name" />
<asp:BoundField DataField="datestamp" HeaderText="Date" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
Text="Download"
ControlStyle-CssClass="btn btn-success"
CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" width="250px" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
And then for downloading the file I have:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["filecontent"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
So what happens now is when I click on the download it always download the first row's file instead of the row I clicked on to download.
I know I need to specify on which row I have clicked in order to download the file, but not sure on how to accomplish it?
Thanks
It is because of this line
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You then need to change from onclick to a grid command:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server"Text="Download"
ControlStyle-CssClass="btn btn-success" CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
</ItemTemplate>
</asp:TemplateField>
And in your code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["id"];
// you can run your query here
}
}
In your case:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
var val = this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = val;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
You need to also add the onrowcommand="ContactsGridView_RowCommand" to your Gridview
<asp:GridView ID="GridView1" runat="server" onrowcommand="ContactsGridView_RowCommand"
I don't know what's wrong with the code i've tried to search for possible reasons but haven't figured out yet what's the problem actually.Now the issue is that my web form contains a gridview in which i've place a footer row which will allow the user to add the data and that data gets added to the database and gets binded to the gridview after clicking on the insert link button,But the problem comes when i fill the data and when press link button insert it adds the data twice in gridview and in database too everytime.Below is my whole code which is performing CRUD operation on gridview:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkBtnInsert" runat="server"
CommandName="Insert">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlactive" runat="server">
<asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm2 : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Delete from PersonalDetail" +
" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue(
"#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue(
"#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue(
"#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
}
}
Please try below code :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView1.RowCommand -= GridView1_RowCommand;
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
I am sorting my date with my sql query and I get a proper result.
But as I apply
gridview.UseAccessibleHeader = true;
gridview.HeaderRow.TableSection = TableRowSection.TableHeader;
to my gridview. The sorted data gets unsorted.
this.gridviewname.MasterTemplate.EnableSorting = true;
this.RadGridView1.MasterTemplate.EnableSorting = True
SortDescriptor descriptor = new SortDescriptor();
descriptor.PropertyName = "Yourcolumnname";
descriptor.Direction = ListSortDirection.Ascending;
this.gridviewname.MasterTemplate.SortDescriptors.Add(descriptor);
descriptorcolumnname As New SortDescriptor()
descriptorShipName.PropertyName = "columnname"
descriptorShipName.Direction = ListSortDirection.Ascending
try this
Try this code which is working fine for me.
-- C# Code here---
<form id="form1" runat="server">
<div>
<h1>Gridview Property of Sorting</h1>
<br />
<asp:GridView ID="gdviewevent" runat="server" AutoGenerateColumns="false" OnSorting="gdviewevent_Sorting" AllowSorting="true">
<HeaderStyle BackColor="YellowGreen" Font-Bold="True" Font-Names="cambria" ForeColor="Black" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:TemplateField HeaderText="Sr No.">
<ItemTemplate>
<span><%#Container.DataItemIndex+1 %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="India Value" SortExpression="IndiaVal">
<ItemTemplate>
<asp:Label ID="lblindiavalue" runat="server" Text='<%#Eval("Column1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date" SortExpression="Registereddate">
<ItemTemplate>
<asp:Label id="lblcreateddate" runat="server" Text='<%#Eval("Registereddate", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
-- Page behind Code ---
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridView();
}
}
protected void FillGridView()
{
string query = "Select Column1, Registereddate from tablename";
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gdviewevent.DataSource = dt;
gdviewevent.DataBind();
ViewState["dirState"] = dt;
ViewState["sortdr"] = "Asc";
}
}
protected void gdviewevent_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
gdviewevent.DataSource = dtrslt;
gdviewevent.DataBind();
}
}
I have a gridview. I need to include a hyperlink to one of the columns so when the user clicks the link a popout should come with option to Edit and save. After the save the gridview should automatically get refreshed.
Following is my Gridview Code:
<asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit"
onrowediting="EmployeeGridView_RowEditing" onrowdeleting="EmployeeGridView_RowDeleting"
onrowupdating="EmployeeGridView_RowUpdating" Width="395px"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="EmployeeGridView_RowDataBound" AllowPaging="True"
onpageindexchanging="EmployeeGridView_PageIndexChanging1" PageSize="5">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText = "Action">
<ItemTemplate>
<asp:CheckBox ID = "chkDelete" runat = "server" AutoPostBack="True"
oncheckedchanged="chkDelete_CheckedChanged" />
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sr.No">
<ItemTemplate>
<asp:Label ID = "lblID" runat = "server" Text = '<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID = "lblEmpName" runat = "server" Text = '<%# Eval("Emp_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experience">
<ItemTemplate>
<asp:Label ID = "lblEmpExp" runat = "server" Text = '<%# Eval("Emp_exp") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID = "lblEmpAddress" runat = "server" Text = '<%# Eval("Emp_address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" ButtonType ="Button"
HeaderText="Edit" ControlStyle-BackColor= "#15524A" >
<ControlStyle BackColor="#15524A"></ControlStyle>
</asp:CommandField>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" HeaderText="Delete" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
The code behind is :
public partial class _Default : System.Web.UI.Page
{
SqlConnection connstr = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
Session["sortBy"] = e.SortExpression;
FillGrid();
}
protected void Page_Load(object sender, EventArgs e)
{
Session["sortBy"] = null;
if (!Page.IsPostBack)
{
FillGrid();
BindGrid();
}
}
public void FillGrid()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
DataTable dt = new DataTable();//object of data table that uses to conatin whole data
dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
EmployeeGridView.DataSource = dt;
EmployeeGridView.DataBind();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EmployeeGridView.EditIndex = -1;
FillGrid();
}
protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
EmployeeGridView.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void EmployeeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("EmployeeUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.Parameters.AddWithValue("#emp_name ", name);
cmd.Parameters.AddWithValue("#emp_exp ", experience);
cmd.Parameters.AddWithValue("#emp_address ", address);
cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
EmployeeGridView.EditIndex = -1;// no row in edit mode
FillGrid();
}
protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.ExecuteNonQuery();
FillGrid();
}
protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
EmployeeGridView.PageIndex = e.NewPageIndex;
FillGrid();
}
protected void buttonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
var lblID = row.FindControl("lblID") as Label;
Response.Write(lblID.Text + "<br>");
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand("Delete from tbl_employee where Emp_id=#emp_id", conn);
// comm.CommandType = CommandType.StoredProcedure;
conn.Open();
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.ExecuteNonQuery();
conn.Close();
}
}
FillGrid();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var lblID = row.FindControl("lblID") as Label;
var lblEmpName = row.FindControl("lblEmpName") as Label;
var lblEmpExp = row.FindControl("lblEmpExp") as Label;
var lblEmpAddress = row.FindControl("lblEmpAddress") as Label;
//Response.Write(lblFirstName.Text + "<br>");
SqlCommand comm = new SqlCommand("EmployeeUpdate", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.Parameters.AddWithValue("#emp_name", EmpName.Text);
comm.Parameters.AddWithValue("#emp_exp", EmpExp.Text);
comm.Parameters.AddWithValue("#Emp_address", EmpAddress.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
EmpName.Visible = false;
EmpExp.Visible = false;
EmpAddress.Visible = false;
}
}
FillGrid();
}
}
For the column Name I need to make a hyperlink and when clicked the popout should come to edit and view data
Not sure I fully understand what do you need but you can check out how modal popup works in MS AJAX toolkit and try to emulate sample code that comes with the download.
I have aspx code of grid view as follows..
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AutoGenerateEditButton="True" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataKeyNames="Machine no." EnableModelValidation="True"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField DataField="Machine no." HeaderText="Machine no."
ReadOnly="True" SortExpression="Machine no." />
<asp:BoundField DataField="Machine Name" HeaderText="Machine Name"
SortExpression="Machine Name" />
<asp:TemplateField HeaderText="Is active?" SortExpression="Is active?">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("[Is active?]") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
SelectedValue='<%# Bind("[Is active?]") %>'>
<asp:ListItem Value="0">Inactive</asp:ListItem>
<asp:ListItem Value="1">Active</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:GridView>
I have defined the logic in code behind as follows..
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
string q = "SELECT machineno AS 'Machine no.',machinename AS 'Machine Name',active AS 'Is active?' FROM machinedetails";
DataTable dt = dtu.table(q, out error);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string mno = e.Keys[0].ToString();
string mname = e.NewValues[0].ToString();
string active = e.NewValues[1].ToString();
string q = "update machinedetails set machinename = '"+mname+"',active='"+active+"' where machineno =" + mno;
Response.Write(q);
e.Cancel=true;
GridView1.EditIndex = -1;
bindgrid();
}
But it throws the error:-
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
can any one help me with this??
Steve --> as per your question i changed my logic as below
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string mno = GridView1.DataKeys[e.RowIndex][0].ToString();
GridView gv = (GridView)sender;
for (int i = 0; i < gv.Columns.Count; i++)
{
DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
}
string mname = e.NewValues[0].ToString();
string active = e.NewValues[1].ToString();
string q = "update machinedetails set machinename = '" + mname + "',active='" + active + "' where machineno =" + mno;
Response.Write(q);
e.Cancel=true;
GridView1.EditIndex = -1;
bindgrid();
}
Now I dont get any error but mname is coming same as datakey
my response.write code produse the following output -->update machinedetails set machinename = '2',active='0' where machineno =2
machinename = '2' should be the value that i have entered in the textbox. Dropdownlist value is comming correct.
I have solved this problem by converting all fields to tempelate fields. But still don't know why this happens.
I think I can explain why you're getting the value of MachineNo in mname.
You're saying:
for (int i = 0; i < gv.Columns.Count; i++)
{
DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
}
Then you say
string mname = e.NewValues[0].ToString();
But what is going into Column[0]? It's Machine No:
<asp:BoundField DataField="Machine no." HeaderText="Machine no." ReadOnly="True" SortExpression="Machine no." />