I'm implementing a search bar to filter GridView1. I followed this tutorial but when it doesnt work. I want to filter the UserID and show only the specific output match the user input. I clicked on search but nothing work, it just refreshed the page and nothing else.
aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Manager.Master" AutoEventWireup="true" CodeBehind="ExceptionReport.aspx.cs" Inherits="Bracelet.ExceptionReport" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-md-10">
<div class="content-box-large">
<div class="panel-heading">
<div class="panel-title">Admin Log Report</div>
</div>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server"/>
<div class="panel-body">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
</div>
</div>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users">
</asp:LinqDataSource>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users" Where="UserRole == #UserRole">
<WhereParameters>
<asp:Parameter DefaultValue="Admin" Name="UserRole" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
</div>
</asp:Content>
Full code .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Bracelet
{
public partial class ExceptionReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT UserID, UserName, UserEmail, logtime FROM [User] WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserID ", txtSearch.Text.Trim());
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
}
}
Not too bad.
but, there are few errors and issues.
first up, you have search button - but it has no "id" assigned.
You probably should get in the habit of simple drag + drop the button in from the tool box.
So, we now have this for the button and the grid:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
NOTE carefull in above, how we gave the button a "ID"
So, our basic code to load up the grid?
FYI: huge love, hugs, high-5's for checking is-post back!!!
(always, always do that!!!).
So, our code to load things up can thus look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.BindGrid();
}
void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT UserID, UserName, UserEmail, logtime FROM [User]", con))
{
// optional text box filter (blank = all)
if (txtSearch.Text != "")
{
cmd.CommandText += " WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Parameters.Add("#UserID", SqlDbType.Text).Value = txtSearch.Text;
}
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Note how we did not need that data adaptor - not needed.
However, we still not created the code stub for the button click (that's why your code is not working - you did not give your button a "id"
So, in the designer - double click on the button. That will create the "event" for you, and jump to the code editor, and we have this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
this.BindGrid();
}
so, in general - don't type in the "event" stubs for a button - double click on the button - it will create + wire it up for you.
Note close, if I flip back to mark-up, the button has become this:
<asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />
Related
I've read through about 50 sites and stackoverflow questions that advise to do what I have in my code below. I've been through many variations on this, and I can't seem to get it to do anything at all.
I've been watching SQL Profiler and nothing is sent at all.
I get no errors.
All I want is a list with checkboxes I can click to change a single setting from 0 to 1. I'm sure it's me, but I'm missing it, and I've spent an embarrassingly long time on this. Thanks for any input.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames="npi"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="provcode" HeaderText="provcode"
SortExpression="provcode" />
<asp:BoundField DataField="npi" HeaderText="npi" SortExpression="npi" />
<asp:BoundField DataField="firstname" HeaderText="firstname"
SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname"
SortExpression="lastname" />
<asp:TemplateField HeaderText="Submit Y/N">
<ItemTemplate>
<asp:CheckBox ID="submitChk" runat="server" Enabled="true" AutoPostBack="True" OnCheckChanged="submit_CheckedChanged"
Checked='<%# Bind("submit") %>'/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DS_SSRS_ReportsConnectionString1 %>"
SelectCommand="SELECT [provcode], [npi], [firstname], [lastname], [submit]
FROM [DRPprovders]
ORDER BY lastname, firstname"
onselecting="SqlDataSource1_Selecting"
>
</asp:SqlDataSource>
</p>
CodeBehind:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
public partial class Pages_ProvSelect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
//int ID = (int)GridView1.DataKeys[row.DataItemIndex].Value;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
}
}
You just need to connect to the database and perform the update "manually" in that CheckedChanged method.
Something like this should work:
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
SqlConnection conn = new SqlConnection("your connection string here");
string updateQuery = "UPDATE DRPprovders SET submit = #submit WHERE npi = #npi";
SqlCommand cmd = new SqlCommand(updateQuery, conn);
// If it's checked, pass 1, else pass 0
cmd.Parameters.AddWithValue("#submit", submitChk.Checked ? 1 : 0);
cmd.Parameters.AddWithValue("#npi", npi);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
You might just be able to pass the boolean value of submitChk.Checked (rather than converting to 1's and 0's like I did), I can't remember now (and I was just typing this off the top of my head, so it's untested).
I'm trying to auto-update my gridview upon clicking the asp:net button. My gridview contains accounts that are waiting to be verified by the admin. The gridview contains a select linkbutton. When the admin selects the link button and clicked the asp:net button, it is suppose to automatically update 'pending' to 'approved'. It will then refresh the gridview and automatically delete the pending account that has been approved.
I used this method response.redirect method
Response.Redirect("AdminVerify.aspx");
but it immediately refreshes my entire page and ignored my ajax scriptmanager
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
that i have added in. With the script manager, i reckon it is not suppose to refresh the entire page. Hence, i'm wondering how do i let a button update the gridview automatically maybe after 3 seconds when it is being clicked.
I tried to input this html code but instead it automatically refresh my page every 5 sec even though i did not click anything
<meta http-equiv="refresh" content="5" >
Source Code :
<%# Page Title="" Language="C#" MasterPageFile="~/Admin.Master" AutoEventWireup="true" CodeBehind="AdminVerify.aspx.cs" Inherits="AdminWebApp.AdminVerify" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Unverified Officer's Account Information<br />
<asp:GridView ID="GVVerify" runat="server" BackColor="#CCCCCC" BorderColor="#999999" Width="100%" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" OnSelectedIndexChanged="GVVerify_SelectedIndexChanged" AutoGenerateSelectButton="True">
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Officer ID :
<asp:Label ID="lblOID" runat="server"></asp:Label>
will be verify upon activation<br />
<br />
<asp:Label ID="lblMsg" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="btnVerify" runat="server" OnClick="btnVerify_Click" Text="Verify" />
<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
TargetControlID="btnVerify"
ConfirmText="Are you sure you would like to verify this police officer?"
OnClientCancel="CancelClick" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
</asp:Content>
Back-end codes :
public partial class AdminVerify : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source =localhost;" +
"Initial Catalog = project; Integrated Security = SSPI";
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT policeid, password, email, nric, fullname, contact, address, location From LoginRegisterPolice where pending='pending'", conn);
da.Fill(ds);
GVVerify.DataSource = ds;
GVVerify.DataBind();
conn.Close();
}
}
protected void GVVerify_SelectedIndexChanged(object sender, EventArgs e)
{
lblOID.Text = GVVerify.SelectedRow.Cells[1].Text;
}
protected void btnVerify_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update LoginRegisterPolice set pending='approved' where policeid='"+lblOID.Text+"'", con);
cmd.ExecuteNonQuery();
lblMsg.Text = "The following officer has been verified.";
Response.Redirect("AdminVerify.aspx");
}
}
}
You can have separate method to load the gridview data. In first time page load you can call this method and also after you done changes on data you can reload the grid by calling this method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
}
private void LoadGrid()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source =localhost;" +
"Initial Catalog = project; Integrated Security = SSPI";
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT policeid, password, email, nric, fullname, contact, address, location From LoginRegisterPolice where pending='pending'", conn);
da.Fill(ds);
GVVerify.DataSource = ds;
GVVerify.DataBind();
conn.Close();
}
protected void btnVerify_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update LoginRegisterPolice set pending='approved' where policeid='" + lblOID.Text + "'", con);
cmd.ExecuteNonQuery();
lblMsg.Text = "The following officer has been verified.";
LoadGrid();
}
As far as I have observed GridViewID.DataBind() will update your grid on the server but it'll not reflect the changes on the browser (client-side). To get the changes reflected without calling Page_Load, just wrap your grid inside an UpdatePanel like this and change its mode to Conditional.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GVVerify" runat="server">
....
....
....
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Then wherever you are binding data to the grid add UpdatePanel1.Update() after it.
C#
....
....
GVVerify.DataSource = ds;
GVVerify.DataBind();
UpdatePanel1.Update(); //this will reflect the changes on client-side
I am working on a college project and have a gridview that I have to add more rows to.
I have two text fields and a button.
Everything seems to be fine except the button part of the code in the .cs file
What am I doing wring?
Its to make a list of Wines with an ID and a Title and a Year:
Wine.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Wine.aspx.cs" Inherits="WineNotProject2.AdminPages.Wine" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<br /><br />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
</Columns>
</asp:GridView>
<p><asp:Label ID="lblTitle" runat="server" Text="Wine Title"></asp:Label><br />
<asp:TextBox ID="txtTitle" runat="server" Width="176px"></asp:TextBox><br />
<p><asp:Label ID="lblYear" runat="server" Text="Wine Year"></asp:Label><br />
<asp:TextBox ID="txtYear" runat="server" Width="176px"></asp:TextBox><br />
</p>
<asp:Button ID="btnAdd" runat="server" Text="Add Wine" OnClick="btnAdd_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [Title], [Year] FROM [Wine]">
</asp:SqlDataSource>
</asp:Content>
Wine.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WineNotProject2.AdminPages
{
public partial class Wine : System.Web.UI.Page
{
private WineEntities10 ent2 = new WineEntities10();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RefreshGrid();
}
}
private void RefreshGrid()
{
GridView2.DataSource = ent2.Wines.ToList();
GridView2.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
}
}
}
UPDATE:
The error message is:
Error 3 'WineNotProject2.AdminPages.Wine' does not contain a definition for 'Year' and no extension method 'Year' accepting a first argument of type 'WineNotProject2.AdminPages.Wine' could be found (are you missing a using directive or an assembly reference?) C:\Visual Studio 2010\Projects\WineNotProject7\WineNotProject2\AdminPages\Wine.aspx.cs 30 20 WineNotProject2
I think you need to call RefreshGrid after you have added the new Wine:
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
RefreshGrid(); // <-------
}
Maybe you also need to parse the year to int:
w2.Year = int.Parse(txtYear.Text);
The problem is you have two classes with same name Wine.
public partial class **Wine** : System.Web.UI.Page
**Wine** w2 = new **Wine**();
Rename ASP.Net page's name to WineList so that
its class name should become public partial class **WineList**
Your code was looking good ,But you miss call the RefreshGrid() end of add button
for
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
**RefreshGrid**
}
If ent2.SaveChanges(); is not working ,then use ent2.SubmitChanges();
I am adding a dropdown to gridview using template field as:
<asp:TemplateField HeaderText="Change Color">
<ItemTemplate>
<asp:DropDownList ID="dropdownid" DataSourceID="sqldatasource_id" DataTextField="username"
BackColor="GrayText" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AppendDataBoundItems="True" runat="server" AutoPostBack="True">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
</asp:DropDownList>
SqlDataSource is:
<asp:SqlDataSource ID="sqldatasource_id" runat="server" ConnectionString="<%$ ConnectionStrings:crudconnection %>"
SelectCommand="SELECT [username] FROM [crudtable]"></asp:SqlDataSource>
Indexchange-Event is as :
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
}
I want to highlight a row when any value from the corresponding dropdownlist is selected.
How can i do it?
Thanks in advance.
i tried it:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red;
But still it is giving a exception as follow when-ever i select any value from any dropdownlist.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
I am getting index number of selected row as already mentioned.can't i increment it from there and can use back-color property too?
Can you give this a try:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red inside your GridView1_SelectedIndexChanged?
It should set the background color of the selected row to a red color
Try GridView_SelectedIndexChanging(). Here is how:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//This is current row. Set it to default color
GridView1.SelectedRow.BackColor = System.Drawing.Color.White;
//This is selected row. Set it to color you wish
GridView1.Rows[e.NewSelectedIndex].BackColor = System.Drawing.Color.Black;
}
Its working.I made changes like below.
int abc=row.rowindex+3;
GridView1.Rows[abc].BackColor = Color.Yellow;
Thanks for support.
function ChangeRowColor(row) {
row = parseInt(row) + 1;
if (previousRow == row)
return; //do nothing
else if (previousRow != null) {
document.getElementById("MainContent_gvSimulationManager").rows[previousRow].style.backgroundColor = previouscolor;
}
previouscolor = document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor;
document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor = "#888888";
previousRow = row;
//Disable and enable Session
var simulationStatus = document.getElementById("MainContent_gvSimulationManager").rows[row].cells[3].innerText;
EnableAndDisable(simulationStatus);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="pub_id" HeaderText="pub_id" />
<asp:BoundField DataField="pub_name" HeaderText="pub_name" />
<asp:BoundField DataField="city" HeaderText="city" />
<asp:BoundField DataField="state" HeaderText="state" />
<asp:BoundField DataField="country" HeaderText="country" />
<asp:ButtonField Text="Click" CommandName="Select" ItemStyle-Width="30" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="msg" runat="server" Text=""></asp:Label>
</div>
</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.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
sql = "select * from publishers";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string pName = GridView1.SelectedRow.Cells[1].Text;
grdCList.SelectedRow.Cells[3].ForeColor = System.Drawing.Color.Red;
}
here is what I'm doing right now:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridViewUserScraps_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")%>' />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridViewUserScraps_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//getting data to bind child gridview.
gv.DataSource = td;
gv.DataBind();
}
so, on button click of the GridView1 I'm updating database and fetching data at same time, there is no any problem in that. But for this I have to Bind/refresh parent(GridView1) Gridview which quite slow process as there are almost 50 rows. what I'm looking is; I want to update or refresh only GridView2 to be shown added comments.
The GridView1.RowCommand is the right event to handle the button's action.
GridView1.RowCommand += (o, e) =>
{
var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
var makeComments = row.FindControl("MakeComments") as TextBox;
int scrapId = Int32.TryParse((string)e.CommandArgument, out scrapId) ? scrapId : 0;
var gridView2 = row.FindControl("GridView2") as GridView;
... place here the code which the comments
gridView2.DataSource = GetCommentsByScrapId();
gridView2.DataBind();
};
On this event (or others), the parent won't bind, unless you specify it.
One common reason the bind a control is by mistakenly call DataBind() every time when the page loads. To prevent this, it is needed to do the binding on the first request of the page and the proper way is to check if the IsPostBack is false.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetUserScraps();
GridView1.DataBind();
}
}
You can refresh only the child gridview without refreshing your parent gridview.
To do it you can do a client side click (ClientClick) to the button and call a jquery function, instead of a server side click.
Then you can update only the items in your child gridview, by calling a web method or http handler class from the particular jquery function via ajax call.
Here your parent grid won't be refreshed since there is no server hit at the button click.
Hope this helps and if you need I will provide sample code for the jquery function.
Try this
foreach(GridViewRow rIndex in GridView1.Rows)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//getting data to bind child gridview.
// if you want to get the row key value use GridView1.DataKeys[rIndex.RowIndex].Value
gv.DataSource = td;
gv.DataBind();
}
I would set the commandname of the button then use the gridview's OnRowCommand event
<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Code Behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="UpdateChildGrid")
{
GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
GridView child = row.FindControl("GridView2") as GridView;
// update child grid
}
}
Doing this from memory so it may not be exact, but should be close enough to give you an idea of where to go
GridView HTML
<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" OnClick="btnPost_Click" />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Code Behind
protected void btnPost(object sender, EventArgs e)
{
//Your code for other operations
//
GridView GridView2 = (GridView)((GridViewRow)((Button)sender).NamingContainer).FindControl("GridView2");
GridView2.DataSource = YourDataBasefetchingFunction();
GridView2.DataBind()
}
Note - Convert the ScrapID DataItem into the DataKey
To Update /refresh only the Child GridView2 in the row where the Update button has been clicked
First of all U need to place the entire GridView1 in Update Panel.
And the child GridView inside another UpdatePanel
Then on the button click U just hav to save ur data and refresh the child grid , in this way only the child grid will be refreshed.
heres a working example.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 10 * from orders", conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateChildGrid")
{
GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
GridView child = row.FindControl("GridView2") as GridView;
string id = row.Cells[0].Text;
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
child.DataSource = dt;
child.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string id = e.Row.Cells[0].Text;
GridView gv = new GridView();
gv = (GridView)e.Row.FindControl("GridView2");
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
gv.DataSource = dt;
gv.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
}
}
And code behind
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="GridView1_SelectedIndexChanged"
AutoGenerateColumns="False"
onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="OrderID" />
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" ButtonType="Button" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>