首先这是界面展示列:
当我点击更新操作后,效果如下:
其中所属区域的复选框为动态绑定,并且已为我们默认勾选了相关选项,具体操作如下:
前台代码:
<tr>
<td class="listTdLeft">所属区域:</td>
<td>
<asp:CheckBoxList ID="chklProvince" runat="server" RepeatDirection="Horizontal">
</asp:CheckBoxList>
</td>
</tr>
后台代码:
/// <summary>
/// 动态绑定省份复选框
/// </summary>
private void BindBoxProvince()
{
PagerSet pagerSet = FacadeManage.aidePlatformFacade.GetProvince(1, Int32.MaxValue, "", "ORDER BY ProvinceId ASC");
chklProvince.DataSource = pagerSet.PageSet;
chklProvince.DataValueField = "ProvinceId";
chklProvince.DataTextField = "ProvinceName";
chklProvince.RepeatDirection = RepeatDirection.Horizontal;
chklProvince.RepeatColumns = 10;
chklProvince.DataBind();
}
以上我们便能动态加载出所有的区域复选框,那么应该怎样才能在页面加载的时候把相关选项默认勾选中了,话不多说,直接上代码:
private void BindData()
{
//获取游戏实体信息
GameArea gameareaEntity = FacadeManage.aidePlatformFacade.GetGameAreaEnttiy(IntParam);
if (gameareaEntity == null)
{
ShowError("游戏信息不存在");
Redirect("GameAreaList.aspx");
return;
}
ddlGame.SelectedValue = gameareaEntity.GameId.ToString();
CtrlHelper.SetText(txtKindID, gameareaEntity.GameId.ToString());
//获取该游戏下对应的省份
SqlConnection conn = new SqlConnection("Server=***;DataBase=***;User ID=***;Password=***");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
conn.Open();
cmd.CommandText = string.Format("SELECT p.ProvinceId FROM dbo.GameArea g LEFT JOIN dbo.Province p ON p.ProvinceId = g.ProvinceId WHERE g.GameID={0}", IntParam);
cmd.Connection = conn;
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
conn.Close();
//循环绑定CheckBoxList选中项
if (chklProvince.Items.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string provincenId = dt.Rows[i][0].ToString();
string[] temp = provincenId.Split(',');
foreach (string item in temp)
{
foreach (ListItem items in chklProvince.Items)
{
if (item == items.Value)//如果相等就选中
{
items.Selected = true;
}
}
}
}
}
}
操作并不难,主要是通过循环来绑定,首先获取该游戏下所属的省份ID,然后将其存为数组来循环遍历,当存在与checkboxlist项的集合中的值相等时,就勾选。