
绑定ID
获取的时候:
Label
lblId=(Label
)this.GridView.Rows[i].FindControl("lblId")//找到当前行寻找,不一定是Rows[i]还可能是Rows[Row.RowIndex],视情况而论
int
ID
=int.Prase(lblId.Text)
这样不就获取到ID了吗
,有了ID其他的不就很简单了吗
页面代码 :<asp:GridView ID="dgvUser" runat="server" Width="254px"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="编号">
<ItemTemplate>
<asp:Label ID="lblId" Text='<%#Eval("id") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CourseName" HeaderText="课程名称" />
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="btnOk" runat="server" Text="确定" onclick="btnOk_Click" />
</p>
<p>
<asp:Label ID="lblInfo" runat="server" Text=""></asp:Label>
</p>
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)//必须加这个,否则取不到值
{
getData()
}
}
private void getData()
{
///读取表Course中的值并显示,表Course中有两列,列名分别是id,courseName
///注意修改数据源名称(.\SQL2008)为你自己的数据库实例名,一般直接写成.
///注意修改数据库连接的用户名与密码
///表Course自己建立
string str=@"Data Source=.\SQL2008Initial Catalog=tempUser ID=sapwd=123456"
SqlConnection conn = new SqlConnection(str)
conn.Open()
SqlCommand cmd = new SqlCommand("select * from Course", conn)
SqlDataAdapter adapter = new SqlDataAdapter(cmd)
DataTable dt = new DataTable()
adapter.Fill(dt)
dgvUser.DataSource = dt
dgvUser.DataBind()
conn.Close()
}
protected void btnOk_Click(object sender, EventArgs e)
{
string ids = ""
foreach (GridViewRow row in dgvUser.Rows)
{
CheckBox chk = row.FindControl("chk") as CheckBox
if (chk.Checked)
{
Label lbl = row.FindControl("lblId") as Label
ids += lbl.Text + ","
}
}
///ids就是最终所选择的记录编号用逗号隔开之后组成的字符串,记住该值最后有一个逗号,在处理时记得将其去掉。如果ids保持为"",则表明用户没有选择任何一个记录
lblInfo.Text = "得到的编号是" + ids
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)