Asp.net动态按钮在第二次单击时触发
本文关键字:单击 第二次 net 动态 按钮 Asp | 更新日期: 2023-09-27 18:16:21
我有2个按钮,应该更新数据库,当它更新页面应该做一个回发与更新的信息,但是…现在它在数据库更新,但页面不更新,直到第二次点击,然后点击之后都是对的,直到我点击另一个选项卡…一切都重演了……顺便说一下,按钮被称为up和down,它们是在创建网格的模板中动态创建的
所以向上/向下按钮是在page_load之后创建的,page_load函数调用loaddisplaygrid(或loadynamicdisplaygrid),然后在loaddisplaygrid(或loadynamicdisplaygrid)函数中构建构建按钮的模板
//page load
protected void Page_Load(object sender, EventArgs e)
{
RadToolBarItem textbxItem = MainRadToolBar.Items.FindItemByText("textbox");
RadTextBox displayName = (RadTextBox)textbxItem.FindControl("displayName");
Session["UserID"] = getUserID();
if (!Page.IsPostBack)
{
if (Profile.ShowFilter)
{
displayMenuBar.Style["display"] = "block";
displayLineBreak.Style["display"] = "block";
}
else
{
displayMenuBar.Style["display"] = "none";
displayLineBreak.Style["display"] = "none";
}
loadDisplay();
loadTemplate();
loadTabs();
saveDefaultOneOffFilter();
checkIfEmpty();
RadTab tab = displayTabs.SelectedTab;
Profile.CurrTemplate = Profile.DefaultTemplate;
if (Profile.DefaultTemplate == dfltTempID) //new user
{
displayName.Text = User.Identity.Name + "_default";
si_display_save_button_Click();
setDefault();
Profile.CurrTemplate = Profile.DefaultTemplate;
updateStatsformat();
Response.Redirect("Display.aspx");
}
if (tab != null)
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = tab.Text;
}
}
else
{
RadTab tab = displayTabs.SelectedTab;
if (tab != null)
{
if (tab.Text == Session["SelectedTabID"].ToString())
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
loadDynamicDisplayGrid(Profile.CurrTemplate);//needs to be different, special just for postback
}
else
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = displayTabs.SelectedTab.Text;
}
//automatically saves when toolbar is not visible....
if (!Profile.ShowFilter) { si_display_save_button_Click(); }
}
}
}
/// <summary>
/// updates and loads the RadGrid for the Display page, depending on which Tab is selected
/// </summary>
private void loadDisplayGrid(int tmpid)
{
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
GridTemplateColumn columntxtbx;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("@tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + Profile.CurrTemplate + "');</script>", false);
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
DataRowView row = (DataRowView)item.DataItem;
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
String value = row["IsDisplayed"].ToString();
chkbx.Checked = (value == "True");
}
}
/// <summary>
/// This is the template for GridTemplateColumn in the display page's grid
/// This represent the column DisplayString
/// Three different kinds of contents are used in each cell of the column depending on StatsValue_Type
/// </summary>
private class MyTemplate : ITemplate
{
//protected RequiredFieldValidator validator1;
//protected RangeValidator validator2;
protected TextBox textBox;
protected DropDownList ddList;
protected Label txtlb;
protected Button up;
protected Button down;
private DisplayGrid.DisplayGridDataTable MyDT = new DisplayGrid.DisplayGridDataTable();
private DisplayGridTableAdapters.DisplayGridTableAdapter MyTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
private Guid myUserID = new Guid();
private int template;
public MyTemplate(DisplayGrid.DisplayGridDataTable DGDT, Guid UserID,int tempid)
{
MyDT = DGDT;
myUserID = UserID;
template = tempid;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//textBox = new TextBox();
ddList = new DropDownList();
txtlb = new Label();
up = new Button();
up.Text = "↑";
down = new Button();
down.Text = "↓";
//textBox.ID = "templateColumnTextBox";
ddList.ID = "templateColumnDDList";
txtlb.ID = "txtLabel";
up.ID = "up";
down.ID = "down";
//textBox.DataBinding += new EventHandler(textBox_DataBinding);
ddList.DataBinding += new EventHandler(ddList_DataBinding);
txtlb.DataBinding += new EventHandler(label_DataBinding);
up.Click += new EventHandler(up_Click);
down.Click += new EventHandler(down_Click);
/*validator1 = new RequiredFieldValidator();
validator1.ControlToValidate = "templateColumnTextBox";
validator1.ErrorMessage = "*";
validator1.Display = ValidatorDisplay.Dynamic;
validator2 = new RangeValidator();
validator2.ControlToValidate = "templateColumnTextBox";
validator2.Type = ValidationDataType.Integer;
validator2.MinimumValue = "0";
validator2.MaximumValue = "12";
validator2.ErrorMessage = "*0-12";
validator2.Display = ValidatorDisplay.Dynamic;*/
//container.Controls.Add(textBox);
container.Controls.Add(ddList);
container.Controls.Add(txtlb);
container.Controls.Add(up);
container.Controls.Add(down);
//container.Controls.Add(validator1);
//container.Controls.Add(validator2);
}
/// <summary>
/// Generates the text boxes when StatsValue_Type is double or percentage
/// Assigns the text and the style
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void textBox_DataBinding(object sender, EventArgs e)
{
TextBox tBox = (TextBox)sender;
GridDataItem container = (GridDataItem)tBox.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "double" || valType == "percentage")
{
tBox.Text = displayStr.Remove(displayStr.IndexOf(" "));
tBox.Font.Bold = true;
tBox.Style["text-align"] = "center";
tBox.Width = 70;
tBox.AutoPostBack = true;
//tBox.TextChanged += new EventHandler(DisplayTextBox_TextChanged);
}
else
{
tBox.Enabled = false;
tBox.Visible = false;
}
}*/
protected void up_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')))+1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
protected void down_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
//ScriptManager.RegisterStartupScript(bt, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' '))) -1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
/// <summary>
/// Generates the drop down lists when StatsValue_Type is Date
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddList_DataBinding(object sender, EventArgs e)
{
DropDownList dl = (DropDownList)sender;
GridDataItem container = (GridDataItem)dl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "Date")
{
dl.Items.Add(new ListItem("MM-DD-YY", "{0:MM-dd-yy}"));
dl.Items.Add(new ListItem("DD-MM-YY", "{0:dd-MM-yy}"));
dl.Items.Add(new ListItem("DD-MMM-YYYY", "{0:dd-MMM-yyyy}"));
dl.SelectedIndex = (displayStr == "MM-DD-YY") ? 0 : (displayStr == "DD-MM-YY") ? 1 : 2;
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
up.Visible = false;
down.Visible=false;
}
/*else if (valType == "double" || valType == "percentage")
{
dl.Items.Add(new ListItem("1 decimals", "{0:f1}"));
dl.Items.Add(new ListItem("2 decimals", "{0:f2}"));
dl.Items.Add(new ListItem("3 decimals", "{0:f3}"));
dl.Items.Add(new ListItem("4 decimals", "{0:f4}"));
dl.Items.Add(new ListItem("5 decimals", "{0:f5}"));
dl.Items.Add(new ListItem("6 decimals", "{0:f6}"));
dl.Items.Add(new ListItem("7 decimals", "{0:f7}"));
dl.Items.Add(new ListItem("8 decimals", "{0:f8}"));
dl.Items.Add(new ListItem("9 decimals", "{0:f9}"));
dl.Items.Add(new ListItem("10 decimals", "{0:f10}"));
dl.Items.Add(new ListItem("11 decimals", "{0:f11}"));
dl.Items.Add(new ListItem("12 decimals", "{0:f12}"));
dl.SelectedIndex =Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')));
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
}*/
else
{
dl.Enabled = false;
dl.Visible = false;
}
}
/// <summary>
/// Generates the words " digits" after the textboxes when StatsValue_Type is double or percentage
/// Generates the label with text of DisplayString when StatsValue_Type is bit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void label_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridDataItem container = (GridDataItem)lbl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "bit")
{
lbl.Text = displayStr;
lbl.Font.Bold = true;
up.Visible = false;
down.Visible = false;
}
else if (valType == "double" || valType == "percentage") {
lbl.Text = displayStr;
lbl.Font.Bold = true;
}
else { lbl.Text = ""; }
}
/// <summary>
/// Handles the event when textbox is sumbitted
/// inefficient at the moment because it is fired for every textbox every tab change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void DisplayTextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
GridDataItem container = (GridDataItem)tb.NamingContainer;
string textCur = ((TextBox)sender).Text + " decimals";
string textOld = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string testing = ((DataRowView)container.DataItem)[MyDT.Columns[0].ColumnName].ToString();
if (textCur != textOld)
{
int value = Convert.ToInt16(((TextBox)sender).Text);
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
string format = "{0:f" + value.ToString() + "}";
string text = value.ToString() + " decimals";
ScriptManager.RegisterStartupScript(tb, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
//MyTA.UpdateDisplayGrid(format, text, myUserID, stats_id);
MyTA.UpdateQuery(format, text, stats_id, (short)template);
}
}*/
/// <summary>
/// Handles the event when dropdownlist selection changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DisplayDDList_IndexChanged(object sender, EventArgs e)
{
string date = ((DropDownList)sender).SelectedItem.Text;
string format = ((DropDownList)sender).SelectedItem.Value;
DropDownList ddl = (DropDownList)sender;
GridDataItem container = (GridDataItem)ddl.NamingContainer;
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
//MyTA.UpdateDisplayGrid(format, date, myUserID, stats_id);
MyTA.UpdateQuery(format, date, stats_id, (short)template);
}
}
//this is called on postback
protected void loadDynamicDisplayGrid(int tmpid)
{
ArrayList oldchkbxList = new ArrayList();
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridTemplateColumn columntxtbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
//GridTemplateColumn columnArrow;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("@tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
//save the old values of the IsDisplayed checkboxes before refresh
foreach (GridDataItem item in StatsFormatGrid.Items)
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
oldchkbxList.Add(chkbx.Checked);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
int itr = 0;
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
chkbx.Checked = (Boolean)oldchkbxList[itr];
DataRowView row = (DataRowView)item.DataItem;
String value = row["IsDisplayed"].ToString();
if (value == "True" && !(Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
else if (value != "True" && (Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
itr++;
}
}
//this is html
<telerik:RadGrid ID="StatsFormatGrid" runat="server" AutoGenerateColumns="False" GridLines="None"
OnDataBound="grid_data_bound" EnableAJAX="true">
<%--ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings--%>
</telerik:RadGrid>
我相信您在数据绑定和ASP.net Page生命周期方面遇到了一个常见的问题。简单地说:您首先将数据绑定,然后更改它。Page_Load
事件处理程序绑定数据,然后处理按下按钮并更改数据库。但是,该控件已经绑定到以前版本的数据,并显示旧的信息。
你应该将你的控件数据绑定在之后,按钮按下已经被处理,数据库中的变化已经被处理。请尝试将数据绑定代码放在Page_PreRender
事件处理程序中。
可以添加
Response.Redirect(Request.RawUrl);
更新完数据库后点击按钮事件
或者调用初始化页面数据的函数。例如
private void Page_Load(...)
{
if(!Page.IsPostBack)
{
InitData();
}
}
private void InitData()
{
//Do init data control in your page
// For exp: binding the grid, combo box....
}
protected void btn_Update_Clicked(...)
{
//1. Update database
//2. Call InitData() function to reload data from database
}