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
Related
I am a beginner and I am creating a crud webpage in asp.net and i can't get the update(save) button working. here is the snippet of my code:
Save and Cancel buttons in Main.aspx
<div height: 334px;" class="gridview">
<asp:GridView ID="RetailInfoGridView"
AutoGenerateColumns="False"
ShowFooter="true"
DataKeyNames="StockKeepingID"
runat="server"
ShowHeaderWhenEmpty="True"
HeaderStyle-ForeColor="White"
AlternatingRowStyle="alt"
EmptyDataText="No Records Found"
AllowSorting="True"
OnRowCommand="RetailInfoGridView_RowCommand"
OnDataBound="RetailInfoGridView_DataBound"
OnRowDataBound="RetailInfoGridView_RowDataBound"
OnRowEditing="RetailInfoGridView_RowEditing"
OnRowCancelingEdit="RetailInfoGridView_RowCancelingEdit"
OnRowUpdating="RetailInfoGridView_RowUpdating"
onRowDeleting="RetailInfoGridView_RowDeleting"
OnSelectedIndexChanged="RetailInfoGridView_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Edit" CommandName="Edit" runat="server" Text="Edit" ToolTip="Edit" />
<asp:Button ID="Delete" CommandName="Delete" runat="server" Text="Delete" ToolTip="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="Add" CommandName="Add" runat="server" Text="Add" ToolTip="Add" />
</FooterTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
...
Main.aspx.cs
string connectionString = "Data Source=102000-LSU-2216;Initial Catalog=loginDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateGridView();
}
}
protected void SearchTextBox_TextChanged(object sender, EventArgs e)
{
/* connect.Open();
string query = "SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'";
adapter = new SqlDataAdapter(query, connect);
table = new DataTable();
adapter.Fill(table);
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
connect.Close();*/
}
protected void SearchButton_Click(object sender, EventArgs e)
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'", connect);
DataTable table = new DataTable();
adapter.Fill(table);
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
}
}
protected void RetailInfoGridView_DataBound(object sender, EventArgs e)
{
}
protected void RetailInfoGridView_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void RetailInfoGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click the link to view Description";
//e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(RetailInfoGridView, "Select$" + e.Row.RowIndex);
}
}
void PopulateGridView()
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
}
else
{
table.Rows.Add(table.NewRow());
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
RetailInfoGridView.Rows[0].Cells.Clear();
RetailInfoGridView.Rows[0].Cells.Add(new TableCell());
RetailInfoGridView.Rows[0].Cells[0].ColumnSpan = table.Columns.Count;
RetailInfoGridView.Rows[0].Cells[0].Text = "No record Found";
}
}
}
protected void RetailInfoGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("Add"))
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "INSERT INTO RetailInfo(StockKeepingUnit,UniversalProductCode,VendorName,ProductName,ProductDesc,RetailPrice) VALUES (#StockKeepingUnit,#UniversalProductCode,#VendorName,#ProductName,#ProductDesc,#RetailPrice)";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#StockKeepingUnit", (RetailInfoGridView.FooterRow.FindControl("skuTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#UniversalProductCode", (RetailInfoGridView.FooterRow.FindControl("upcTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#VendorName", (RetailInfoGridView.FooterRow.FindControl("vnTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductName", (RetailInfoGridView.FooterRow.FindControl("pnTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductDesc", (RetailInfoGridView.FooterRow.FindControl("pdTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#RetailPrice", (RetailInfoGridView.FooterRow.FindControl("rpTextBoxFooter") as TextBox).Text.Trim());
command.ExecuteNonQuery();
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('New Record Added');", true);
}
}
}
catch (Exception ex)
{
}
}
protected void RetailInfoGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
RetailInfoGridView.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void RetailInfoGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
RetailInfoGridView.EditIndex = -1;
PopulateGridView();
}
protected void RetailInfoGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "UPDATE RetailInfo SET StockKeepingUnit=#StockKeepingUnit,UniversalProductCode=#UniversalProductCode,VendorName=#VendorName,ProductName=#ProductName,ProductDesc=#ProductDesc,RetailPrice=#RetailPrice WHERE StockKeepingID=#id";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#StockKeepingUnit", (RetailInfoGridView.Rows[e.RowIndex].FindControl("skuTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#UniversalProductCode", (RetailInfoGridView.Rows[e.RowIndex].FindControl("upcTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#VendorName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("vnTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pnTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductDesc", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pdTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#RetailPrice", (RetailInfoGridView.Rows[e.RowIndex].FindControl("rpTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
command.ExecuteNonQuery();
RetailInfoGridView.EditIndex = -1;
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Updated');", true);
}
}
catch (Exception ex)
{
}
}
protected void RetailInfoGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "DELETE FROM RetailInfo WHERE StockKeepingID = #id";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
command.ExecuteNonQuery();
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Deleted');", true);
}
}
catch (Exception ex)
{
}
}
Whenever I run the program, I edit values to a specific row and then I click the save button, it does not do anything. I have read other answers that said to have a !postback and DataKeyNames in the code but I already have the postback in Main.aspx.cs and the DataKeyNames on Main.aspx. I don't know if the error comes on the .aspx or on the .aspx.cs. Have I done something wrong on the code? any help would be highly appreciated. Thank you.
UPDATE:
I have solved the problem. instead of writing "save" variables:
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
I changed it to "update":
<EditItemTemplate>
<asp:Button ID="Update" CommandName="Update" runat="server" Text="Update" ToolTip="Update" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
Although I do not know why it worked, but it did the job!
If you know why "save" did not work and and "update" worked, I would really appreciate it if you tell me so i can be enlightened.
Thank you for all who helped.
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?
<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">
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);
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.