2015-01-31 50 views
-1

我的代碼是我怎樣才能對象綁定到一個gridview

public Emp GetEmpByEmpno(int empno) 
{ 
    using (con) 
    { 
     if (con.State == ConnectionState.Closed) 
     { 
      con.ConnectionString = constr; 
      con.Open(); 
     } 
     cmd.CommandText = "sp_emp_GetempByEmpno"; 
     cmd.Parameters.Clear(); 
     cmd.Parameters.AddWithValue("@eno",empno); 
     dr=cmd.ExecuteReader(); 
     Emp obj=null; 

     while(dr.Read()) 
     { 
      obj=new Emp(); 
      obj.Empno=int.Parse(dr["Empno"].ToString()); 
      obj.Ename=dr["Ename"].ToString(); 
      obj.Sal=dr["Sal"].ToString(); 
      obj.Deptno=int.Parse(dr["Deptno"].ToString()); 

     } 

     return obj; 
    } 
} 

在這裏,我取基於員工編號的記錄,每當我通過EMPNO在文本搜索按鈕的onClick,各個僱員應在網格視圖中顯示。我如何將對象綁定到網格視圖?

Employee obj=EmpDeptBus.GetEmployeeByEmpno(int.Parse(txtEmpno.Text));    
gvemp.DataSource = c; 
gvemp.DataBind(); 

回答

1

你應該能夠只是說

gvemp.DataSource = obj; 

這的確是所有你需要做的的對象綁定。 此外,改變你的

while(dr.Read()) 

if(dr.Read()) 

你只能期待一個記錄,因此只能取一個。在返回到調用函數之前,還要將您的返回obj放在您使用的外部以確保所有內容都妥善處理。

嘗試確保txtEmpno.Text在您嘗試將其傳遞給此方法之前保留一個int值,否則它將炸燬。永遠不要信任用戶輸入。你可以這樣做:

int empNo = 0; 
if(int.TryParse(txtEmpNo.Text.Trim(), out empNo) 
{ 
// then call the function and bind your grid using the empNo as the 
// variable holding the employee number. 
} 
else 
{ 
    // otherwise handle the fact that the user entered a non-numeric. 
}