I have a simple gridview with image button to update value of one of gridview column, by problem is whenever I click the image button it refresh the wholw page and I want the gridview only to be refreshed with updated value, I tried using UpdatePanel but it also refresh the whole page,
any help will be apprechiated.
aspx code:
<form id="form1" runat="server" >
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" PageSize="5">
<Columns >
<asp:BoundField DataField="req_id" HeaderText="request ID" SortExpression="req_id" />
<asp:BoundField DataField="req subject" HeaderText="request subject" SortExpression="req_subject" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
aspx.cs code:
protected void Button_update(object sender, ImageClickEventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(#"Data Source= DESKTOP-U9437PU; initial Catalog = Mydb; Integrated Security =True;"))
{
sqlCon.Open();
string sql = "update requests_table set stat_id = '2' where req_id ='" 5 "'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
sqlCon.Close();
}
GridView1.DataBind();
}
You need to set UpdateMode Conditional:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button_update" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" PageSize="5">
<Columns >
<asp:BoundField DataField="req_id" HeaderText="request ID" SortExpression="req_id" />
<asp:BoundField DataField="req subject" HeaderText="request subject" SortExpression="req_subject" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Then you should work call UpdatePanel1.Update(); as following:
protected void Button_update(object sender, ImageClickEventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(#"Data Source= DESKTOP-U9437PU; initial Catalog = Mydb; Integrated Security =True;"))
{
sqlCon.Open();
string sql = "update requests_table set stat_id = '2' where req_id ='" 5 "'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
sqlCon.Close();
}
GridView1.DataBind();
UpdatePanel1.Update();
}
Try this:
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" OnClientClick="javascript:void(0);" />
And this
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
Related
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.
I want to update only selected row from my grid view when i press linked button but it is not working on my end .
Here is my Design Page
<asp:GridView ID="grdCompanyUsers" runat="server"
DataKeyNames="id_company_user,nm_company_username"
AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-
BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images
/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CompUserID" runat="server" Width="15"
Text='<%#Eval("id_company_user")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="companyusername" runat="server" Width="51"
Text='<%#Eval("nm_company_username")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compName" runat="server" Width="56" Text='<%#Eval("nm_company_name")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compDesc" runat="server" Width="129" Text='<%#Eval("nm_company_desc")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compEmail" runat="server" Width="103px"
Text='<%#Eval("nm_company_email_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compAddress" runat="server" Width="153px"
Text='<%#Eval("nm_company_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxStatus" runat="server" Width="15px" Enabled="false"
Text='<%#Eval("ind_active")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false"
CommandArgument='<%#Eval ("id_company_user")%>'
OnClick="btnEdit_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDeny" Font-Underline="false" CommandName="Deny"
CommandArgument='<%# Eval("id_company_user") %>'
OnClick="btnDeny_Click">Deny</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my code behind the aspx page
protected void btnEdit_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int i = Convert.ToInt32(row.RowIndex);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update ref_registration_company_user
set ind_active=1 where id_company_user=id_company_user", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is Design View :
I just want that only selected row should be affected in database.
I will be thank full for help.
you need to set the id_company_user value in your sql statement. use parameters as below.
SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=#id_company_user", conn);
cmd.Parameters.AddWithValue("#id_company_user", id);
you need to get current row id_company_user value check below SO question and answer, you can use
OnRowCommand of GridView and CommandArgument property
GridView: Get datakey of the row on button click
<asp:GridView ID="grdCompanyUsers" runat="server" DataKeyNames="id_company_user,nm_company_username" AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound"
OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false" CommandArgument='<%#Eval ("id_company_user")%>' CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id= int.Parse(e.CommandArgument);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=id_company_user", conn))
{
cmd.Parameters.AddWithValue("#id_company_user", id);
cmd.ExecuteNonQuery();
}
}
}
Can you please check once your update query where clause,
Check the sqlDataSource control for this problem, you can add the select and update command for populate and update rows your GridView on there.
Maybe this example could be you useful
http://asp-net-example.blogspot.mx/2008/12/aspnet-gridview-and-sqldatasource.html
In my first load of my aspx page, I have a GridView that are filled.
In my ASPX page I handle the click event on my radio button
$("#ctl00_contentConteudo_rbBuscas_1").click(function () {
$.get("../Gerenciar/ListaUsuarioProvisorio.aspx?Documentacao=s&r=" + Math.random(2), {}, function (data) {
});
});
So, this force to pass in my page load again when my radio button is clicked.
ASPX
<div id="infoGrid" runat="server">
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
<asp:SqlDataSource ID="dsGrid" runat="server"></asp:SqlDataSource>
</div>
CODE BEHIND
In my code behind, my PageLoad just call my CarregaLista method, that fill my GridView
protected void CarregaLista()
{
string documentacao = Request.QueryString["Documentacao"].ToString();
if (documentacao.Equals("s"))
{
string select = string.Empty;
select += "SELECT top 10 San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, San_Usuario.DescricaoCargo1, "
+ "CONVERT(varchar, San_Usuario.DataHora, 103) AS DataHora "
+ "FROM San_Usuario "
+ "JOIN San_Credenciada "
+ "ON San_Usuario.Credenciada_Id = San_Credenciada.Credenciada_Id "
+ "WHERE San_Usuario.Excluido = 0 "
+ "GROUP BY San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, "
+ "San_Usuario.DescricaoCargo1, San_Usuario.DataHora "
+ "ORDER BY San_Usuario.DataHora ASC ";
dsGrid.ConnectionString = c.Con;
dsGrid.SelectCommand = select;
dsGrid.DataBind();
grdImoveis.DataBind();
dsGrid.Dispose();
}
}
}
WITH UPDATE PANEL
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:RadioButton ID="RadioButton2" runat="server" Text="Curso Básico Netimóveis" />
<asp:RadioButton ID="RadioButton1" runat="server" Text="Buscar Lista de Presença" />
<asp:RadioButton ID="rdBuscas" runat="server" OnCheckedChanged="Click" Text="Curso Documentação Imobiliária" />
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
<asp:SqlDataSource ID="dsGrid" runat="server"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdBuscas" />
</Triggers>
</asp:UpdatePanel>
My problem is that my GridView don't refresh with this query.
How can I solve this ?
You can use Ajax Tretament - based on UpdatePanel, Triggers and UpdateMode="Condition"
You can use this code (Adjust your GridView and Id of your radio button on trigger)
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ModeUpdate="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server">
<Columns>
......
</Columns>
</asp:GridView>
<asp:RadioButton ...../>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="YourRadioButtonId" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
I have following tables in my database:
SuggestionsLog Table: ID, Title, Description.
Employee Table: Username, Name
Divisions Table: DivisionCode, DivisionName
I want to show table that consists of SuggestionID, SuggestionTitle, EmployeeName and DivisionName only and when the user clicks on the SuggestionTitle, a pop-up window will be displayed with the description of the suggestion.
Since I am ASP.NET beginner developer, I tried to follow this tutorial to get it but I failed.
What I did is the following:
ASP.NET Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkSuggestionTitle"
Text='<%#Eval("Title") %>'
OnClick="lnkSuggestionTitle_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />--%>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionName" HeaderText="Division"
SortExpression="DivisionName" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btnModalPopUp" style="display:none" />
<AjaxToolkit:ModalPopupExtender ID="modalPopUpExtender1"
runat="server" TargetControlID="btnModalPopUp" PopupControlID="pnlPopUp" BackgroundCssClass="modalBackground"
OkControlID="btnOk" X="20" Y="100">
</AjaxToolkit:ModalPopupExtender>
<asp:Panel runat="server" ID="pnlPopUp" CssClass="confirm-dialog">
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionName
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode">
</asp:SqlDataSource>
Code-Behind:
protected void lnkSuggestionTitle_Click(object sender, EventArgs e)
{
LinkButton lnkSuggestionTitle = sender as LinkButton;
string strSuggestionTitle = lnkSuggestionTitle.Text;
string strConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
string strSelect = "SELECT ID, Title, Description FROM dbo.SafetySuggestionsLog";
SqlConnection sqlCon = new SqlConnection();
sqlCon.ConnectionString = strConnectionString;
SqlCommand cmdSuggestionDetails = new SqlCommand();
cmdSuggestionDetails.Connection = sqlCon;
cmdSuggestionDetails.CommandType = System.Data.CommandType.Text;
cmdSuggestionDetails.CommandText = strSelect;
cmdSuggestionDetails.Parameters.AddWithValue("#Title", strSuggestionTitle);
sqlCon.Open();
SqlDataReader dReader = cmdSuggestionDetails.ExecuteReader();
GridView1.DataSource = dReader;
GridView1.DataBind();
sqlCon.Close();
modalPopUpExtender1.Show();
}
Everything is going well and smooth, but in the website, when I clicked on one of the titles, I did not get the ModalPopUp. Also, I got an error notification at the left bottom corner in the Internet Explorer browser, which when I opened it, it gave me the following description:
**
Sys.ArgumentNullException: Value cannot be null. Parameter name:
elements
**
I don't know why this is happened. Any help please?
This issue is usually a bad OkControlID or CancelControlID (via here), which could be "btnOk" in this case.
Following on from #PeterX's suggestion, yes your Panel declaration is missing a lot of things.
I would redo this like something as this, which is what I use inside another even bigger GridView control.
<ajaxToolkit:ModalPopupExtender ID="mpeEndorsed" runat="server"
BackgroundCssClass="modalBackground"
PopupControlID="pnlEndorsed"
OkControlID="btnEndorsed"
CancelControlID="btnNotEndorsed"
PopupDragHandleControlID="dvHdr"
Drag="true"
TargetControlID="cbEndorsed">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="pnlEndorsed" runat="server" CssClass="pnlEndorsed" style="display:none">
<div id="dvHdr">
<asp:Label ID="Label3" runat="server">** CONTACT LOG **</asp:Label>
</div>
<div id="dvBody">
<table style="text-align:center; width:100%">
<tr>
<asp:GridView ID="gvContactLog" runat="server" ForeColor="#333333" GridLines="None" AllowPaging="true" PageSize="8" Font-Size="X-Small" CellPadding="4" AllowSorting="True" AutoGenerateColumns="False">
</asp:GridView>
</tr>
<tr>
<td>
<asp:Button ID="btnEndorsed" runat="server" Text="YES" />
<asp:Button ID="btnNotEndorsed" runat="server" Text="NO" />
</td>
</tr>
</table>
</div>
</asp:Panel>
Note the GridView inside the pop-up Panel is a skeleton, that has to be built up either from JavaScript or CodeBehind to get it to be useful.
Defining a Gridview in its entirety (with DataSource, fields, etc) inside a pop-up panel, that's inside another even bigger Gridview (as in my case), does not work! You will get a muddled looking screen and things all over the place. I guess it's a limitation of the AjaxToolKit, to mix client-side and server-side functionality.
I have a data list control which is placed inside a content place holder.
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="Server">
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DataList ID="dlProdocut" runat="server" RepeatColumns="3" EditItemIndex="-1"
RepeatDirection="Horizontal" OnItemDataBound="dlProdocut_ItemDataBound">
<ItemTemplate>
<asp:Table ID="Table1" runat="server" border="0" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell Height="10" HorizontalAlign="Center" VerticalAlign="Top">
</asp:TableCell>
</asp:TableRow>
<%--Image--%>
<asp:TableRow>
<asp:TableCell Height="150" Width="7" HorizontalAlign="left" VerticalAlign="top">
<asp:HyperLink ID="hyrProductImg" runat="server">
<img alt='<%# DataBinder.Eval(Container.DataItem,"Title")%>' src="../images/<%# DataBinder.Eval(Container.DataItem,"SmallImage") %>" border="0" width="226" height="166" />
</asp:HyperLink>
</asp:TableCell>
<asp:TableCell Width="5"> </asp:TableCell>
</asp:TableRow>
<%--Title--%>
<asp:TableRow>
<asp:TableCell Height="45" Width="7" CssClass="product-name" HorizontalAlign="Center"
VerticalAlign="Top">
<strong> <%# DataBinder.Eval(Container.DataItem, "Title")%></strong>
</asp:TableCell>
</asp:TableRow>
<%--ShortDescription--%>
<asp:TableRow>
<asp:TableCell Width="7" HorizontalAlign="Justify" VerticalAlign="Top" CssClass="testimonial-text">
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"ShortDescription")%>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<%--Read More--%>
<asp:TableRow>
<asp:TableCell HorizontalAlign="Left">
<asp:HyperLink ID="lnkProductDetails" CssClass="read-more" runat="server">Read More →</asp:HyperLink>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Height="60" HorizontalAlign="Justify" VerticalAlign="Top" CssClass="testimonial-text">
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="dlProdocut" />
<asp:AsyncPostBackTrigger ControlID="btnNext" />
</Triggers>
</asp:UpdatePanel>
<asp:Label ID="lblPage" runat="server" Text="" />
<asp:Button ID="btnPrevious" runat="server" Text="<<" />
<asp:Button ID="btnNext" runat="server" Text=">>" OnClick="btnNext_Click" />
<asp:Panel ID="BottomPager_Panel" runat="server">
</asp:Panel>
</asp:Content>
On click of next button i am doing paging on the control and navigating to the next page.
On page load i am doing this
if (!IsPostBack)
{
pageCount = 1;
PageNo = 1;
startPage = 6 * (PageNo - 1) + 1;
lastPage = startPage + 5;
bindDataList();
}
This is my code for bindDataList
public void bindDataList()
{
string source = ConfigurationManager.ConnectionStrings["Cad-B"].ToString();
SqlConnection con = new SqlConnection(source);
SqlCommand cmd = new SqlCommand("sp_GetProductPagingByMenuId", con);
//cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "sp_GetProductPagingByMenuId";
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#startPage", startPage);
cmd.Parameters.Add("#lastPage", lastPage);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dlProdocut.DataSource = dt;
dlProdocut.DataBind();
}
On click of next button i have written the following code
protected void btnNext_Click(object sender, EventArgs e)
{
dlProdocut.DataSource = null;
dlProdocut.DataBind();
pageCount++;
PageNo = pageCount;
startPage = 6 * (PageNo - 1) + 1;
lastPage = startPage + 5;
bindDataList();
}
Problem i am facing is that it every time shows me the same content that is loaded the first time on the page. When i debug the code i can see that the data list is loaded with the new records but it is not reflected on the page i tried removing caching but it dint help. The moment i removed the next button from the trigger section it is giving me the proper record but the complete page is getting post back which i dont want. This is the removed code
<asp:AsyncPostBackTrigger ControlID="btnNext" />
Please help i am stuck with this since long. I am new to this technology. Thanks in advance.
Try :
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DatalistId$btnNext" />
</Triggers>