Windows VistaWindows 2003ADO.NETWindows 2000ASPWindows XPCSSWindows FormsC# 2.0C# 3.0HTML中级开发JavascriptWindows.NETASP.NETC#
在没有 PostBack 或 AJAX 的情况下获取 DataGrid 行值






4.77/5 (7投票s)
如何在不进行回发或 AJAX 操作的情况下获取 DataGrid 行值。


引言
本文主要描述了如何在不进行回发或调用 AJAX 的情况下获取 DataGrid 行值。
背景
在某些情况下,我们需要在从 DataGrid 中选择特定行后,将字段从子窗口填充到父窗口。 想法是将 DataGrid 值传递到父窗口,而无需回发或调用 AJAX。 我在不同的论坛上问过这个问题,但每个人最终都建议使用 AJAX。 在进行了一些搜索和探索后,我发现了一些其他方法来做到这一点。
使用代码
我创建了一个场景,其中父窗口有一些可以从子窗口填充的字段。 在 DataGrid 上获取搜索结果后,我们选择结果,父窗口字段将使用所选结果填充。
这可以通过使用 OnItemDataBound 事件来完成。 在事件处理程序函数中,我们注册 OnMouseOver、OnMouseOut 函数用于装饰目的,并且 OnClick 函数注册一个 SetMouseClick 函数,将参数传递到父窗口。
private void dgEmployee_ItemDataBound(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
                        ListItemType.AlternatingItem)
  {
    e.Item.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
    e.Item.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
    string FirstName = e.Item.Cells[0].Text.ToString();// first column value
    string LastName = e.Item.Cells[1].Text.ToString() ;// Second 
    string HireDate = e.Item.Cells[2].Text.ToString() ;// third
    string Job = e.Item.Cells[3].Text.ToString() ;// fourth
    string Publisher = e.Item.Cells[4].Text.ToString() ; // fifth 
    string City = e.Item.Cells[5].Text.ToString() ; // sixth
    
    e.Item.Attributes["onclick"] = 
       "javascript:setMouseClick('"+FirstName+"','"+LastName+"','" + 
       HireDate+"','"+Job+"','"+Publisher+"','"+City+"');";
  }
}
现在,我们有一个 JavaScript 函数,它在 DataGrid Click 事件上将参数传递给父窗口。 由于这是一个模态弹出窗口,我们可以通过 window.returnValue 将选定的行值返回到父窗口。
//JavaScript Function 
function setMouseClick(first_name,last_name,hire_date,job,publisher,city ) {
    var array = new Array();
    array[0]=first_name;
    array[1]=last_name;
    array[2]=hire_date;
    array[3]=job;
    array[4]=publisher;
    array[5]=city;
    window.returnValue=array;
    window.close();    
}
在父窗口侧,我们有一个 JavaScript 函数,它接受来自子窗口的返回值,并在文本框中显示返回值。 OnSearch 函数在单击搜索超链接时触发。
//JavaScript Function 
function OnSearch()
{
    var value = window.showModalDialog('\Popup.aspx','','');
    if(value != null)
    {
        document.getElementById('txtFirstName').value = value[0];
        document.getElementById('txtLastName').value = value[1];
        document.getElementById('txtHireDate').value = value[2];
        document.getElementById('txtJob').value = value[3];
        document.getElementById('txtPublisher').value = value[4];
        document.getElementById('txtCity').value = value[5];
    }
}
就这样。 谢谢!


