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.
Related
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?
I found implementation of my problem on a side but i dont know why it isn't working. When i put some value into textbox it should do me a postback but it does not.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView2">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
And code behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE amount > 1000";
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
string SelectCommand = "SELECT * " +
" FROM client_inf WHERE client_name Like '" + txt.Text + "%'"
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
}
http://www.infosearchshop.com/21-gridview-search-as-you-type-with-ajax
I would suggest to update the AsyncPostBackTrigger as follow to match the ID of the textbox = TextBox1 with the AutoPostBack reference but the control needs to be outside the UpdatePanel
<asp:AsyncPostBackTrigger ControlID ="TextBox1" EventName ="TextChanged" />
I would also suggest trying to use PostBackTrigger instead. This is mostly used for controls inside the UpdatePanel that makes a full post back
<asp:PostBackTrigger ControlID="TextBox1" />
TextBox 's id and GridView's ID don't match .
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txt" />
</Triggers>
<ContentTemplate>
<asp:TextBox runat="server" ID="txt" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:GridView runat="server" ID="GridView1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="regon" HeaderText="Regon" SortExpression="regon" ItemStyle-Font-Size="10px" />
<asp:BoundField DataField="nip" HeaderText="NIP" SortExpression="nip" ItemStyle-Font-Size="10px" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txt.Attributes.Add("onkeyup", "javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)");
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
private DataTable GetDataSource()
{
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("regon", typeof(string));
dt.Columns.Add("nip", typeof(string));
dt.Rows.Add("Name-1", "regon-1", "nip-1");
dt.Rows.Add("Name-2", "regon-1", "nip-1");
dt.Rows.Add("Name-3", "regon-1", "nip-1");
dt.Rows.Add("Name-4", "regon-1", "nip-1");
dt.Rows.Add("Name-5", "regon-1", "nip-1");
dt.Rows.Add("Name-6", "regon-1", "nip-1");
dt.Rows.Add("Name-7", "regon-1", "nip-1");
return dt;
}
protected void txt_TextChanged(object sender, EventArgs e)
{
if (txt.Text != "")
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
}
<asp:UpdatePanel ID="upExec" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<button type="button" runat="server" id="btnExec" onserverclick="btnExec_Click" class="btnAll btnExec">Execute SQL Job</button>
<asp:Label ID="lblEMsg" runat="server" ClientIDMode="Static" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upGV" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView EmptyDataText="No Provider Exists" ID="gvData" runat="server" ClientIDMode="Static" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderStyle-Width="5%" DataField="Name" HeaderText="Name" />
<asp:BoundField HeaderStyle-Width="5%" DataField="ID" HeaderText="ID" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
if (!Page.IsPostBack)
{
ViewState["sortOrder"] = "Asc";
ViewState["sortExp"] = "Due Date";
ShowGridView("Name", "Asc");
}
public void ShowGridView(string sortExp, string sortDir)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
SqlDataAdapter sda = new SqlDataAdapter(strQuery, sc);
DataSet ds = new DataSet();
sda.Fill(ds);
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
gvData.DataSource = dv;
gvData.DataBind();
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upGV.Update();
}
public void btnExec_Click(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
using (SqlCommand scd = new SqlCommand())
{
scd.CommandText = "MySP";
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.ExecuteNonQuery();
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
using (SqlConnection sc = new SqlConnection(floString))
{
try
{
sc.Open();
SqlCommand scd = new SqlCommand();
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.CommandText = "msdb.dbo.sp_start_job";
scd.Parameters.AddWithValue("#job_name", "JobName");
using (scd)
{
scd.ExecuteNonQuery();
ShowGridView("Name", "Asc");
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upExec.Update();
}
When the page first loads, I can see the GridView. When I click the btnExec, the GridView disappears and it displays "No Provider Exists". When I check the source of the page the data is still there.
How can I resolve it so when the button is clicked, it performs the stored procedure and reloads the GridView with the new data.
Looks like you should move the call to ShowGridView() in your btnExec_Click() method to outside the outer "using" statement, right before the call to upExec.Update().
On my case, I had to add this attribute to the panel that was wrapping my GridView to keep it visible and working, every time I was clicking on a row to select it, it kept disappearing :
<asp:Panel EnableViewState="True">
For my 'UserName' field i am checking the exist name, if exist then will throw an error in label.so how to disable button's click event or postback?
protected void txtUserName_TextChanged(object sender, EventArgs e)
{
try
{
string userName = txtUserName.Text;
if (connection.State == ConnectionState.Closed)
connection.Open();
command = new SqlCommand();
command.CommandText = "Get_UserName";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#userName", userName);
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
lblUserNameError.Text = "Alredy Exist";
lblUserNameError.Visible = true;
//btnSave.Enabled = false;
//btnSave.onClientClick="return false";
someID.Attributes.Add("onClick", "return false;");
}
else
{
lblUserNameError.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally //Close db Connection if it is open....
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
above by three ways I still getting postback to page on button click.
My textbox is inside an UpdatePanel also the Button has to be inside an UpdatePanel or else it won't be refreshed.
<asp:updatepanel id="uptxtUserName" runat="server" xmlns:asp="#unknown"><contenttemplate>
<asp:textbox id="txtUserName" runat="server" tabindex="8" autopostback="true">
ontextchanged="txtUserName_TextChanged"></asp:textbox>
<asp:label id="lblUserNameError" runat="server" visible="false" forecolor="Red"></asp:label>
<asp:requiredfieldvalidator id="reqUName" controltovalidate="txtUserName" errormessage="Required" class="error" runat="server" forecolor="Red">
</asp:requiredfieldvalidator>
</contenttemplate>
<triggers>
<asp:asyncpostbacktrigger controlid="txtUserName" eventname="TextChanged" />
<asp:asyncpostbacktrigger controlid="btnSave" eventname="Click" />
<asp:asyncpostbacktrigger controlid="btnCancel" eventname="Click" />
</triggers>
</asp:updatepanel>
<pre lang="xml"><asp:UpdatePanel ID="upbtnSave" runat="server"><ContentTemplate>
<asp:Button ID="btnSave" Text="Save" runat="server" TabIndex="31" class="btn btn-success" onclick="btnSave_Click"></asp:Button>
<asp:Button ID="btnCancel" Text="Cancel" CausesValidation="false" runat="server" TabIndex="32" class="btn" onclick="btnCancel_Click"></asp:Button>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnCancel" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="txtUserName" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
then code behind side will work like below
protected void txtUserName_TextChanged(object sender, EventArgs e)
{
try
{
string userName = txtUserName.Text;
if (connection.State == ConnectionState.Closed)
connection.Open();
command = new SqlCommand();
command.CommandText = "Get_UserName";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#userName", userName);
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
lblUserNameError.Text = "Alredy Exist";
lblUserNameError.Visible = true;
btnSave.OnClientClick = "return false;";
}
else
{
lblUserNameError.Visible = false;
btnSave.OnClientClick = "return true;";
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally //Close db Connection if it is open....
{
if (connection.State == ConnectionState.Open)
connection.Close();
connection.Close();
command.Dispose();
}
}
Should the btnSave.Enabled = false; be inside the if statement and not the else?
Seems to me that now you're disabling the button if same usernames are not found.
You can use YourTargetButton.Enabled = false;
if (reader.HasRows)
{
lblUserNameError.Text = "Alredy Exist";
lblUserNameError.Visible = true;
YourTargetButton.Enabled = false;
}
When using the function: btnSave.Enabled = false;, after text changed event fired, is the button disabled in HTML page?
However, you can use this solution:
<script type="text/javascript">
$(document).ready(function () {
if ($('#<%=Label1.ClientID%>').is(":visible")) {
$('#<%=btnSave.ClientID%>').attr('disabled', 'disabled');
}
else {
$('#<%=btnSave.ClientID%>').removeAttr('disabled');
}
});
</script>
The script should be added into page which contains your btnSave.
You should add <script src="js/jquery-1.11.0.js" type="text/javascript"> in to head tag:
<head runat="server"> <script src="js/jquery-1.11.0.js" type="text/javascript"> </head>.
I don't know if this is the case but if your textbox is inside an UpdatePanel also the Button has to be inside an UpdatePanel or else it won't be refreshed
Also could you post the controls declaration
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);