[英]Avoid postback when getting dropdownlist value c# asp
我在C#中動態創建了一個dropdownlist
(在asp中沒有代碼):
DropDownList myDDL = new DropDownList();
這不能從pageLoad()
調用,因為每次刷新頁面時都不會加載它。 然而它每次加載另一個dll的OnPostback( OnSelectedIndexChanged()
)所以我不能這樣做!IsPostBack
。
在以下情況下創建此dll:
另一個dropdownlist
的值使用OnSelectedIndexChanged()
填充GridView
<asp:DropDownList id ="select1" name="assignGetForm" runat="server" class="selectClass" AutoPostBack="True" OnSelectedIndexChanged="populateGridView">
在GridView
上運行一個函數OnRowDatabound()
(當上面的OnIndexChanged()
填充它時)在GridView
填充myDDL
<asp:GridView id="GridView1" name="GridView1" onrowdatabound="populateCellsDDL" runat="server"></asp:GridView>
我現在正嘗試使用onclick()
事件按鈕訪問myDDL
的值 - 但是這總是回發並刷新頁面,因此myDDL
消失,當我將值打印到控制台時,它只是給出我的第一個值select activity
而不是一個我真的選擇了。
如果更改這些值,我將如何獲取這些值,因為pageLoad()
上沒有填充此dll。 我試過看AJAX然而我不確定如何通過這個查看c#值。 我試過以及viewstates
但我沒有運氣,因為它不會填充在pageLoad()
。
我想,如果要訪問動態創建的控件的值,則需要在每個回發中重新綁定網格。
我嘗試使用以下示例代碼模擬情況,並且我能夠成功訪問該值。
ASPX代碼
<asp:DropDownList ID="select1" name="assignGetForm" runat="server" class="selectClass" AutoPostBack="True" />
<asp:GridView ID="GridView1" name="GridView1" OnRowDataBound="GridView1_DataBound" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
C#代碼落后
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
FillMainDll();
if (!IsPostBack || GridView1.Rows.Count > 0)
BindGrid();
}
private void FillMainDll()
{
select1.DataSource = new int[] { 1, 2, 3 };
select1.DataBind();
}
private void BindGrid()
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
for (int i = 1; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name - " + i.ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var myDDL = new DropDownList();
myDDL.ID = "myDDL";
myDDL.DataSource = GetGridRowDdlData();
myDDL.DataBind();
e.Row.Cells[1].Controls.Add(myDDL);
}
}
private IEnumerable<string> GetGridRowDdlData()
{
var data = new List<string>();
for (int i = 1; i < 4; i++)
{
data.Add("Name - " + i * int.Parse(select1.SelectedValue));
}
return data;
}
protected void Button1_Click(object sender, EventArgs e)
{
var sb = new System.Text.StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
var myDDL = row.FindControl("myDDL") as DropDownList;
if (myDDL != null)
{
sb.AppendFormat("{0}<br/>", myDDL.SelectedValue);
}
}
Response.Write(sb.ToString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.