首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

利用 JavaScript 選擇 GridView 列

     編輯:關於ASP.NET

客戶端模擬 GridView 列選取:變色反白 + 隱藏欄位回傳鍵值

頁面佈局

<input id="hdnEmailID" type="hidden" value="0" runat="server" />
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvUsers_RowDataBound">
  <Columns>
    <asp:BoundField DataField="Email" HeaderText="郵件" ReadOnly="True" />
    <asp:BoundField DataField="Name" HeaderText="姓名" ReadOnly="True" />
  </Columns>
</asp:GridView>
<asp:Button ID="btnSelect" runat="server" OnClick="btnSelect_Click" Text="Select" />

JavaScript 選取邏輯

<script type="text/javascript">
var lastRowSelected, originalColor;
function GridView_selectRow(row, emailID) {
    var hdn = document.form1.hdnEmailID;
    hdn.value = emailID;
    if (lastRowSelected != row) {
        if (lastRowSelected != null) {
            lastRowSelected.style.backgroundColor = originalColor;
            lastRowSelected.style.color = 'Black';
            lastRowSelected.style.fontWeight = 'normal';
        }
        originalColor = row.style.backgroundColor;
        row.style.backgroundColor = 'BLACK';
        row.style.color = 'White';
        row.style.fontWeight = 'normal';
        lastRowSelected = row;
    }
}
function GridView_mouseHover(row) { row.style.cursor = 'hand'; }
</script>

RowDataBound 註冊事件

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.ID = e.Row.Cells[0].Text; // Email 作為 ID
        e.Row.Attributes["onclick"] = "GridView_selectRow(this,'" + e.Row.Cells[0].Text + "')";
        e.Row.Attributes["onmouseover"] = "GridView_mouseHover(this)";
    }
}

伺服器端取得選中值

protected void btnSelect_Click(object sender, EventArgs e)
{
    Response.Write(hdnEmailID.Value); // 取得選中列的 Email
}

優點

  • 無 PostBack 即時視覺回饋。
  • 隱藏欄位攜帶鍵值,伺服器端按鈕事件直接讀取。
  • 相容舊版 GridView,無需 CheckBoxField 或 SelectCommand。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved