我正在使用gridview,我希望能够点击每一行,以便能够显示我正在显示的对象中的另一个字段。感觉它很容易解决,但也许我很愚蠢,因为我无法在任何地方找到它......
ASP代码:
<asp:GridView ID="gvMessages" runat="server" AutoGenerateColumns = "false"
CaptionAlign="NotSet" CellPadding="5">
<Columns>
<asp:BoundField HeaderText="Avsändare" DataField="Sender" />
<asp:BoundField HeaderText="Ämne" DataField="Head" />
</Columns>
</asp:GridView>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
gvMessages.DataSource = con.GetMails(con.GetId(Membership.GetUser().UserName));
gvMessages.DataBind();
}
不确定是否所有这些都是问题的必要条件,但这是我的wcf-project中的方法,它使用对象信息填充我的复合类
public List<MailInfo> GetMails(int id)
{
using (var client = new datingEntities())
{
var result = client.Mail.Where(x => x.SentTo == id).Select(x => new MailInfo
{
Message = x.Mail1,
Reciever = x.SentTo,
Read = (bool)x.IsRead,
Sender = (int)x.SentFrom,
Head = x.Subject
}).ToList();
return result;
}
}
复合级:
[DataContract]
public class MailInfo : Mail
{
[DataMember]
public string Message { get; set; }
[DataMember]
public int Reciever { get; set; }
[DataMember]
public bool Read { get; set; }
[DataMember]
public int Sender { get; set; }
[DataMember]
public string Head { get; set; }
}
答案 0 :(得分:4)
您应该仅对GridView
if(!Page.IsPostBack)
进行数据绑定。
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvMessages.DataSource = con.GetMails(con.GetId(Membership.GetUser().UserName));
gvMessages.DataBind();
}
}
如果您想在点击中选择一行,可以使用javascript:
protected void gvMessages_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
现在,只要用户点击行中的某个位置,您就可以处理SelectedIndexChangedEvent
:
protected void gvMessages_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
}
答案 1 :(得分:1)
您应该使用OnSelectedIndexChanged
事件。
<asp:GridView ID="gvMessages" runat="server" AutoGenerateColumns = "false"
OnSelectedIndexChanged="gvMessages_SelectedIndexChanged"
CaptionAlign="NotSet" CellPadding="5">
<Columns>
<asp:BoundField HeaderText="Avsändare" DataField="Sender" />
<asp:BoundField HeaderText="Ämne" DataField="Head" />
</Columns>
</asp:GridView>
然后在事件的定义中,您可以检索所选项目并从那里做任何您需要的事情。
protected void gvMessages_SelectedIndexChanged(object sender, EventArgs e)
{
if (ContactsGridView.SelectedIndex >= 0)
ViewState["SelectedKey"] = gvMessages.SelectedValue;
else
ViewState["SelectedKey"] = null;
}
中的示例