Update gridview by clicking a button asp.net c# - c#

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

Related

Cannot search on gridview C# aspnet

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" />

Is there a way to update and delete gridview fields in ASP.NET connected by MySQL

I cannot find a descend code for my gridview update and delete.
And also my Web form is connected with Mysql
I have tried some youtube tutorials but nothing helps. Or Am I just not getting the procedure
I expect 2 buttons "Update"&"Delete" respectively for a gridview which gets values from Mysql Database
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test1.aspx.cs" Inherits="test1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" >
<Columns>
<asp:BoundField DataField="br_id" HeaderText="Brand ID" SortExpression="br_id" />
<asp:BoundField DataField="br_name" HeaderText="Brand Name" SortExpression="br_name" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
Source Code
public partial class test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String mycon = "Data Source=localhost; Initial Catalog=ecommerce; User Id=root;password='' ";
String myquery = "Select * from brand";
MySqlConnection con = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}

How to update the page without reload using update panel ?AP.NET C#

I have a gridview which contains an edit and a delete command.
I would like that when I click on edit, update the value, and click on delete that the value is deleted from database and the page is not reloaded.
Now, I use update panel and script manager but the page is reloaded again, the Update panel is not working. And my other problem is when I put <form runat="server"></form> form tag before gridview then it's working fine, the gridview shows, but when I remove this tag then an error appears:
object reference not set instance object.
My aspx code is :
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate>
<form runat="server"></form>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Database_id" Height="184px"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" style="margin-left: 181px" Width="361px"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Database Name">
<EditItemTemplate>
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Eval("Database_Name") %>' Width="192px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Database_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtdescription" runat="server" Height="24px"
Text='<%# Eval("Description") %>' Width="209px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operations" ShowDeleteButton="True"
ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
</ContentTemplate></asp:UpdatePanel>
</asp:Content>
and my aspx.cs code is :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
private void binddata()
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(con))
{
string user = Session["name"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd2.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
SqlDataAdapter da = new SqlDataAdapter("SELECT Database_id,Database_Name,Description,Date FROM Create_db WHERE User_ID='" + ID + "'", cnn);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
binddata();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
delete(id);
GridView1.EditIndex = -1;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtDatabaseName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDatabaseName");
TextBox txtdescription = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdescription");
updatedb(txtDatabaseName.Text, txtdescription.Text, id);
GridView1.EditIndex = -1;
binddata();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
binddata();
}
private void updatedb(string dbname, string Dis, int id)
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
using (SqlConnection cnn = new SqlConnection(con))
{
string query = "UPDATE Create_db SET Database_Name='" + dbname + "',Description='" + Dis + "' WHERE Database_id='" + id + "' ";
SqlCommand cmd = new SqlCommand(query, cnn);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
private void delete(int id)
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
using (SqlConnection cnn = new SqlConnection(con))
{
string query = "DELETE FROM Create_db WHERE Database_id='" + id + "' ";
SqlCommand cmd = new SqlCommand(query, cnn);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
Your code is not well formatted, the UpdatePanel is outside the form, and gridview also is outside the form. It must be like that...
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView>
...
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
First things first:
<%-- Your code (fragment) --%>
<EditItemTemplate>
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Eval("Database_Name") %>' Width="192px"></asp:TextBox>
</EditItemTemplate>
Eval is ReadOnly (OneWay) binding. It should be
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Bind("Database_Name") %>' Width="192px"></asp:TextBox>
Next. I would recommend you to use <asp:SqlDataSource... which takes all dirty work to itself (select, update, and delete). You can sent your UserID parameter to the parameters like this:
<asp:Literal ID="userId" runat="server" Visible="false"></asp:Literal>
...
<asp:SqlDataSource ID="sqlDS"...
<SelectParameters>
<asp:ControlParameter ControlID="userId" PropertyName="Text" Name="ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
...
In GridView add DataSourseID="sqlDS"
In Page_load set value userId.Text=ID.ToString();
Try this way.

Select a value from dropdown list with the ID and display the ID selected in gridview

My problem is that I can only select the first index, but I want to select all values in the dropdown list. I tried multiple combinations of selectedvalue or selectedindexchanged, but it still not working.
<%# Page Language="C#" Debug="true"%>
<%# import Namespace="System.Data" %>
<%# import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="text/css" href="style1.css"/>
<script language="c#" runat="server">
string str = "Data Source=.;uid=sa;pwd=123;database=InventoryRouting";
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
string com = "Select * from Plant";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
drop.DataSource = dt;
drop.DataBind();
drop.DataTextField = "PlantID";
drop.DataValueField = "PlantID";
drop.DataBind();
}
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("select * from Plant where PlantID = '"+ drop.SelectedValue +"'", con);
SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
Adpt.Fill(dt);
grid.DataSource = dt;
grid.DataBind();
}
</script>
</head>
<body>
<center>
<h1 style="background-color:red; width:500px;height:50px;">Plant Information</h1><hr>
<form id="form1" runat="server">
<div id="right">
Choose Plant ID to View Information<asp:DropDownList ID="drop" runat="server" Width="100px" AutoPostBack="true" OnSelectedIndexChanged="Button1_Click1"> </asp:DropDownList>
<br />
<br />
<!--<asp:Button ID="Button1" runat="server" Text="View" OnClick="Button1_Click1" Style="height: 26px" />-->
<br />
<br />
<asp:GridView ID="grid" runat="server" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</div>
</form>
</center>
</body>
</html>
How can I select all ID from my dropdown list? Please help me
you need to check Page.IsPostBack property before data binding. when you click button, page will postback and if you not put that condition new data will be loaded again. you will lost selection
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){ // add this line
SqlConnection con = new SqlConnection(str);
string com = "Select * from Plant";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
drop.DataSource = dt;
drop.DataBind();
drop.DataTextField = "PlantID";
drop.DataValueField = "PlantID";
drop.DataBind();
}
}

how to update only child GridView?

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>

Categories

Resources