我有2个应该更新数据库的按钮,当它更新页面时应该使用更新的信息进行回发,但是...现在它在数据库中更新好了,但页面没有更新直到第2个点击,之后的点击都没问题,直到我点击了anohter标签......一切都重复发生了......顺便说一下上下调用按钮,它们是在创建网格的模板中动态创建的
所以up_ down按钮是在page_load之后构建的,page_load函数调用loaddisplaygrid(或loaddynamicdisplaygrid),然后在loaddisplaygrid(或loaddynamicdisplaygrid)函数中构建构建按钮的模板
//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>
答案 0 :(得分:1)
我相信你遇到了数据绑定和ASP.net Page life cycle的常见问题。简单地说:首先对数据进行数据绑定,然后进行更改。 Page_Load
事件处理程序绑定您的数据,之后按下按钮并更改数据库。但是,该控件已绑定到先前版本的数据并显示旧信息。
您应该对控件进行数据绑定 AFTER 已按下按钮,并且已处理数据库中的更改。尝试将数据绑定代码放在Page_PreRender
事件处理程序中。
答案 1 :(得分:0)
您可以添加
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
}