2012-05-03 2 views
3

내가 저장 프로 시저 저장 프로 시저를 통해DataGridview 현재 행의 열 값을 가져 오는 방법은 무엇입니까?

ALTER PROCEDURE [dbo].[spGetAllCustumer] 

    AS 
    SET NOCOUNT ON 
SET XACT_ABORT ON 
    BEGIN TRAN 
    BEGIN 
SELECT  Customer.CustID, Customer.CustName, Customer.CompanyName, Customer.CompanyRealtion, Contract.ContractID, Contract.ContractDate, 
        '$'+ CONVERT(varchar,Contract.totalPayment,1), '$'+ CONVERT(varchar,Contract.monthlyInstallment,1), '$'+ CONVERT(varchar,Contract.totalCommission,1), Contract.ContractDuration, Contract.PaymentMode, Contract.Description, 
        Customer.Disable 
FROM   Customer INNER JOIN 
        Contract ON Customer.CustID = Contract.CustID 
WHERE  (Customer.Disable = 'false') 

END 
commit 

내가

con.ConnectionString = "Data Source=MRDEVELOPER;Initial Catalog=Crystal_Accounts;Integrated Security=True"; 
      SqlCommand com = new SqlCommand(); 
      com.Connection = con; 
      com.CommandText = "spGetAllCustumer"; 
      com.CommandType = CommandType.StoredProcedure; 
      com.Parameters.Clear(); 
      con.Open(); 
      SqlDataReader dr = com.ExecuteReader(); 
      DataTable dt = new DataTable(); 
      dt.Load(dr); 
      dataGridView1.DataSource = dt; 

내가 선택하려면이 코드를 동적으로있는 gridview를 채우는거야됩니다 채우는되어있는 gridview가있는의 WinForm이 custID, contractID, selectedRow의 총 지불액 내가 어떻게 할 수 있는지, 두 번째 질문은 내가 사용한 storedprocedure에 사용 된 통화 기호에 관한 것인가, 아니면 올바른 방법인가? 값을 얻으려면

답변

3

Volody가 지적했듯이, SelectedRows 속성을 사용하여 필요한 모든 것을 얻을 수 있습니다. 그러나 문제의 열의 색인을 알지 못할 수도 있습니다 (대개 검색어와 동일한 순서로 생성되기 때문에 열의 별칭을 올바르게 지정해야합니다). 열의 텍스트를 사용하여 셀 :

foreach(DataGridViewRow row in DataGridView1.SelectedRows) 
{ 
    // Do something with row.Cells["CustID"].Value; 
    // Do something with row.Cells["ContractID"].Value; 
    // Do something with row.Cells["TotalPayment"].Value; 
} 

내가 추천하는 다른 방법은 SQL 쿼리 대신 DataGridView에 서식을 지정하는 것입니다. 프레젠테이션/UI 계층에서 데이터 액세스/비즈니스 논리 계층을 분리 할 때 일반적으로 가장 좋은 방법입니다. 이렇게하는 방법은 문제의 열에 대해 DataTable의 DataColumn에 DataFormatString을 지정하는 것입니다. 이 특정한 경우에, 당신은이 작업을 수행 할 것입니다 :

... 
DataTable dt = new DataTable(); 
dt.Load(dr); 
dt.Columns["TotalPayment"].DataFormatString = "C"; 
dt.Columns["MonthlyInstallment"].DataFormatString = "C"; 
dt.Columns["TotalCommission"].DataFormatString = "C"; 
dataGridView1.DataSource = dt; 

코드에서 모든 일의 단점은 당신이 (당신은 런타임 동안 모든 것을 테스트해야 의미있는 디자인 타임 지원을받을 수 없다는 것입니다있는 시간이 많이 소요될 수 있음). 이는 ORM이 사용되는 이유 중 하나입니다 (예 : VS DataSet Designer, LINQ2SQL 디자이너, EntityFramework 등). 따라서 데이터베이스 쿼리/개체를 디자인 타임에 지원할 수 있습니다. 디자인 타임에 이러한 데이터 클래스를 직접 UI 컨트롤에 바인딩하고 심지어 코드 실행 전의 표시 레이어에 대한 모든 사항 (예 : 숨겨진 열, 추가 계산 열, 특수 열 서식, 조건부 행/열/셀 페인팅 등).

단지 0.02 달러입니다.

+0

** dr ** ** ** dt.Load (dr) ** ** – mepk

+0

죄송합니다. 데이터 주소 – mepk

+0

방금 ​​코드를 가져 와서이 세 줄을 추가했습니다. 열의 별칭을 올바르게 지정하십시오. 그렇지 않으면 UI 레이어의 추측 일뿐입니다. – SPFiredrake

2

사용 SelectedRows 수집

int columnOfcustID = 0; // change this to correct custID column index 
int columnOfcontractID = 1; // change this to correct contractID column index 
int columnOftotalpayment = 2; // change this to correct totalpayment column index 
foreach(DataGridViewRow row in DataGridView1.SelectedRows) 
{ 
    Console.WriteLine(row.Cells[columnOfcustID].Value); 
    Console.WriteLine(row.Cells[columnOfcontractID].Value); 
    Console.WriteLine(row.Cells[columnOftotalpayment].Value); 
} 
0

당신은 select 이벤트를 오버라이드 (override)합니다. 당신이

<asp:TemplateField HeaderText="Total Payment"> 
<itemTemplate> 
    <asp:label id="lblTotalPayment" Text='<%# Eval("TotalPayment","{0:C}") %>' runat="server" /> 
</itemTemplate> 
</asp:TemplateField> 

그러나 다음과 같은 구문을 사용하여 라벨이나 다른 컨트롤로 달러 금액을 평가할 수있는 TemplateField를 사용

void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e) 
{ 

    GridViewRow row = GridView1.Rows[e.NewSelectedIndex]; 

    //get value from cells 
    String var = row.Cells[1].Text; 

    //do something with the value or pass the values to a function here 
    DoSomething(var); 
} 

또한 코드의 열을 만들 수 있습니다 ...

그 길을 가기 위해서는 모든 필드를 설정해야합니다.

+0

이것은 WebForms GridView가 아니라 WinForms DataGridView를위한 것입니다. 그러나, 논리는 당신이 어쨌든 제안하고있는 것과 매우 유사합니다. – SPFiredrake

관련 문제