updatepanel trigger cause fullpostback instead partial postback - c#

I want partial postback(asyncpostback) instead fullpostback.but it's not working. Dynamically created checkbox where check or unchecked checkbox cause fullpostback
but it should be asyncpostback.Here is my code.....
<asp:CheckBoxList ID="chkList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="chkList_SelectedIndexChanged"
ClientIDMode="AutoID">
</asp:CheckBoxList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
C# code:
private static readonly string constring = ConfigurationManager.ConnectionStrings["ConnectionStrRead"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand com = new SqlCommand("Select * from Category");
com.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
int dtRows = dt.Rows.Count;
List<string> itemList = new List<string>();
for (int i = 0; i < dtRows; i++)
{
//itemList = new List<string>();
string item = dt.Rows[i]["CategoryName"].ToString() + "(" + dt.Rows[i]["CreateUser"].ToString() + ")";
itemList.Add(item);
}
chkList.DataSource = itemList.ToArray();
chkList.DataBind();
con.Close();
}
}
protected void chkList_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = true;
lblMessage.Text = string.Empty;
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
lblMessage.Text += item.Text + "<br/>";
}
}
}

Can u check your scriptmanager EnablePartialRendering attribute. It must be EnablePartialRendering="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnablePartialRendering="true" EnableScriptGlobalization="true" > </asp:ScriptManager>
If problem is not about that u can try add AsyncPostBackTrigger in code behind
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkList);

Related

Listbox in UpdatePanel doesn't trigger the second time

The list box in the below updatePanel triggers the postback only once, for example if I select pre-Purchase on ddlroot it loads the appropriate data on ddlchild, but if I select post-order again it doesn't load the data needed.
<asp:UpdatePanel ID="UpdatePanel5" ChildrenAsTriggers="true" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlroot" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlchild" EventName="Textchanged" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td>
<asp:ListBox ID="ddlroot" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlroot_SelectedIndexChanged">
<asp:ListItem Value="pre-purchase" Text="Pre-Purchase"></asp:ListItem>
<asp:ListItem Value="post-purchase" Text="Post-Purchase"></asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:ListBox ID="ddlchild" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Below would be the server side code where based on the ddlroot selection the data will be fetched from MySql database,
protected void ddlroot_SelectedIndexChanged(object sender, EventArgs e)
{
ddlchild.Items.Clear();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
if (ddlroot.SelectedValue == "pre-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(prePurchase) from prepurchase WHERE prePurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["prePurchase"].ToString();
item1.Value = sdr1["prePurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
else if(ddlroot.SelectedValue == "post-purchase")
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd1 = new MySqlCommand())
{
cmd1.CommandText = "select distinct(postPurchase) from prepurchase WHERE postPurchase IS NOT NULL";
cmd1.Connection = conn;
conn.Open();
using (MySqlDataReader sdr1 = cmd1.ExecuteReader())
{
while (sdr1.Read())
{
ListItem item1 = new ListItem();
item1.Text = sdr1["postPurchase"].ToString();
item1.Value = sdr1["postPurchase"].ToString();
ddlchild.Items.Add(item1);
}
}
conn.Close();
}
}
}
//UpdatePanel5.Update();
}
How can I fix this?

ListBoxItemSelected event not firing C# Asp.net?

I have a listboxitems i want that when i select value then page redirect to other page.I use onSelectedIndex property event function but it's not working.I search on google alot i find many solutions like autopostback property='true'. I apply all solutions but still not working.My listbox values coming from database and it load fine but page not redirecting to other page.
Here is my code aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server"></form>
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px"
style="margin-left: 247px; margin-top: 68px"
onselectedindexchanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</div>
</asp:Content>
and here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getdata();
}
}
public void getdata()
{
string user = Session["name"].ToString();
SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True");
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);
SqlCommand cmd = new SqlCommand("USE db_compiler SELECT Database_Name FROM Create_db WHERE User_ID='" + ID + "'", cnn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string value = row["Database_Name"] + "";
ListBox1.Items.Add(value);
}
}
}
public void ListBox_Changed(object sender, EventArgs e)
{
Session["value"] = ListBox1.SelectedValue;
Response.Redirect("CreateTable.aspx");
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
}
I also use 'breakpoint' to check that event is firing or not but event is not firing.I don't know why?????
All asp.net controls have to be inside a <form> that has a runat="server" attribute. Move the closing tag of your form to the end of the content and it should work. Like this:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<div class="select-db">
<form runat="server">
<label style="position:relative; font-weight:bold;bottom:230px; left:450px; color:White;">Select Database</label>
<asp:ListBox ID="ListBox1" runat="server" Height="202px" Width="262px" style="margin-left: 247px; margin-top: 68px" OnSelectedIndexChanged="ListBox_Changed" AutoPostBack="true" EnableViewState="True" >
</asp:ListBox>
</form>
</div>
</asp:Content>
Also remember you can only have one <form> with runat="server".

asp.net cascading dropdownlists always selects first item

I am using three DropDownLists in a page. And I am binding data to DDL1(DropDownList1) on pageload using if(!Page.IsPostBack) condition too. And on DDL1 selectedIndexChanged Event I am binding data to DDL2 and its working fine. But when I try to do the same to DDL3 & DDL2 (Like binding data to DDL2 on SelectedIndexChanged Event of DDL2) always DDL2 selects the first item only if I select random also DDL2 still goes first item. Here All 3 DDLs are AutoPostback-true, Vistate-Enabled
Here is my code:
ASPX - Code..
<form id="form1" runat="server">
<div>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
</div>
</form>
.CS Code...
public partial class getcolumns : System.Web.UI.Page
{
private SqlConnection con;
private SqlDataAdapter da;
private DataTable dt;
private DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string query = " SELECT name, dbid FROM sys.sysdatabases where dbid > 4 order by name ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
ds = new DataSet();
da.Fill(dt);
DropDownList1.DataSource = dt.DefaultView.ToTable(true, "name", "dbid");
//DropDownList1.DataValueField = "dbid";
DropDownList1.DataTextField = "name";
DropDownList1.DataBind();
}
catch (Exception) { }
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList2.Items.Clear();
string query = " SELECT TABLE_CATALOG, TABLE_NAME FROM " + DropDownList1.SelectedItem + ".INFORMATION_SCHEMA.tables ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
ds = new DataSet();
da.Fill(ds);
DropDownList2.DataSource = ds; // dt.DefaultView.ToTable(true, "TABLE_NAME", "TABLE_CATALOG");
//DropDownList2.DataValueField = "TABLE_CATALOG";
DropDownList2.DataTextField = "TABLE_NAME";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch { }
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList3.Items.Clear();
string query = " SELECT TABLE_NAME, COLUMN_NAME FROM " + DropDownList1.SelectedItem + ".INFORMATION_SCHEMA.columns where TABLE_NAME = '" + DropDownList2.SelectedItem + "' ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
da.Fill(dt);
DropDownList3.DataSource = dt.DefaultView.ToTable(true, "TABLE_NAME", "COLUMN_NAME");
//DropDownList3.DataValueField = "TABLE_NAME";
DropDownList3.DataTextField = "COLUMN_NAME";
DropDownList3.DataBind();
}
catch (Exception) { }
}
}
Edit :-
It worked well when I Ignore the 'DataValueField' of DDLs
Thank All to your support...
This could be multiple autopostback events, so when it fires firstly ddl1 goes and overwrites selected item in second one. When second event comes it is reset to default state.
You could try using same event method on both and depending on the caller populate stuff.
Make use of these two (object sender, EventArgs e) :D
Try using this code, its working Fine for me.
aspx
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" >
</asp:DropDownList>
</div>
</form>
.cs
public List<string> list1 { get; set; }
public List<string> list2 { get; set; }
public List<string> list3 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
list1 = new List<string> { "a", "b", "c" };
DropDownList1.DataSource = list1;
DropDownList1.DataBind();
}
catch (Exception) { }
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
list2 = new List<string> { "1a", "1b", "1c" };
DropDownList2.DataSource = list2;
DropDownList2.DataBind();
}
catch { }
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
list3 = new List<string> { "2a", "2b", "2c" };
DropDownList3.DataSource = list3;
DropDownList3.DataBind();
}
catch (Exception) { }
}
I Just removed your default options in the dropdowns and removed viewstatemode and use your databinding instead of lists.

asp.net DataList select DropDownList value

I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item

UpdatePanel Gridview not updating

For some reason, I can't get the Gridview in the Updatepanel to refresh after I've made changes. can someone help?
I'm using the ToolkitScriptManager control and the UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView blah...
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DeleteButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="IBUpUp" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="IBDownDown" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="IBUp" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="IBDown" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="EditProfile" EventName="Click" />
</Triggers>
Cs Page
protected void Unnamed3_Click(object sender, ImageClickEventArgs e)
{
int rowIndex = GridView1.SelectedIndex;
GridViewRow gvr = GridView1.SelectedRow;
if (rowIndex >= 0)
{
//delete
String GridViewOne = GridView1.DataKeys[rowIndex].Value.ToString();
//delete image
string imagename = gvr.Cells[2].Text;
string pathToImage = #"C:\Images\";
pathToImage = pathToImage + imagename;
if (System.IO.File.Exists(pathToImage))
{
// Use a try block to catch IOExceptions, to
// handle the case of the file already being
// opened by another process.
try
{
System.IO.File.Delete(pathToImage);
}
catch (System.IO.IOException m)
{
Console.WriteLine(m.Message);
return;
}
}
int bannerid = Convert.ToInt32(GridViewOne);
SqlDataReader sdr = null;
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand("Tool_DeleteBannerAds", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#BannerID";
param1.Value = bannerid;
cmd.Parameters.Add(param1);
conn.Open();
sdr = cmd.ExecuteReader();
sdr.Close();
UpdatePanel1.Update();
GridView1.DataBind();
}
else
{
//don't do anything
//keep
//Response.Redirect("Default.aspx");
}
}
change the order:
GridView1.DataBind();
UpdatePanel1.Update();
Here is my code for your question
ASPX FILE
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Name List" DataField="EmpName" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" />
</form>
</body>
CODE BEHIND FILE
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var Employee = new { EmpID = 1, EmpName = "Rahul Jain", Department = "IT", Age = 33, Address = "Hello" };
var customerList = (new[] { Employee }).ToList();
customerList.Add(new { EmpID = 2, EmpName = "Sheetal Jain", Department = "IT", Age = 33, Address = "Hello" });
GridView1.DataSource = customerList;
GridView1.DataBind();
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
try
{
var Employee = new { EmpID = 1, EmpName = "Rahul Jain", Department = "IT", Age = 33, Address = "Hello" };
var customerList = (new[] { Employee }).ToList();
customerList.Add(new { EmpID = 2, EmpName = "Sheetal Jain", Department = "IT", Age = 33, Address = "Hello" });
customerList.Add(new { EmpID = 2, EmpName = "Minakshi Jain", Department = "IT", Age = 33, Address = "Hello" });
GridView1.DataSource = customerList;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
This Code Dosent Created the postback for me hope it will work for you as well....
As an alternative, you could set the UpdateMode parameter to "Always" (which is the default) to allow any web control that triggers a postback to automatically update the GridView.
This saves you a few lines of code (configuring the triggers) but will also help if you dynamically add controls to your GridView that will also trigger postback events on your page.

Categories

Resources