2017-02-22 32 views
0

上午具有串格(TStringGrid)與2-柱和1行(Property: ColCount = 2 & Rowcount = 1 TStringGrid細胞[ACOL,AROW],一個文本。閱讀來自其通過DrawText函數產生的「OnDrawCell」事件

代碼OnDrawCell事件:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; 
    Rect: TRect; State: TGridDrawState); 
    var 
    Parametertext : string; 
begin 
    case ACol of 
    0 : Parametertext := 'Test'; 
    1 : Parametertext := 'Test1'; 
    end; 
    stringgrid1.Brush.Color := clBtnFace; 
    stringgrid1.Font.Color := clWindowText; 
    stringgrid1.Canvas.FillRect(Rect); 
    DrawText(stringgrid1.Canvas.Handle, PChar(parameterText), -1, Rect, 
     DT_SINGLELINE); 
end; 

當我運行應用程序,我得到了以下的輸出: Sample Output

問:

當我嘗試使用來獲取文本StringGrid1.Cells[0,0]StringGrid1.Cells[1,0]

我除了「測試」 &「Test1的」,但它總是給人一種空字符串「」。

如何使用StringGrid.Cells[aCol,aRow]從字符串網格中獲取文本?

+1

我同意@ Dsm的回答,但爲什麼你要在第一個地方在DrawCell事件中做什麼?爲什麼不在代碼中分配單元格的值,然後離開網格來完成繪圖? – MartynA

+0

該文本不存在。您已繪製(使用** DRAWText **)一些您分配給本地變量的文本。爲什麼你會希望局部變量的內容能夠神奇地存儲在單元格中?你所做的只是**繪製它**。這裏是你正在尋找的魔法 - 刪除你的OnDrawCell處理程序,併爲表單創建一個OnCreate處理程序。添加這兩行:'StringGrid1.Cells [0,0]:='Test'; StringGrid1.Cells [1,0]:='Test1';'。魔法。 –

+0

這是一個現有的代碼,不是新的代碼,我沒有權限修改它。相同類型的代碼與大型應用程序集成,並試圖從自動化工具中獲取網格值(如測試完成)... – bejarun

回答

3

您正在生成文本來繪製它,但不存儲它。不過,您還需要設置stringGrid.Cells值,但可能不在OnDrawCell事件中。

想想你的變量參數文字。它是在退出時被摧毀的局部變量。你在任何地方都無處可救。那麼爲什麼你會期望它奇蹟般地出現在單元格屬性中呢?

0

要做到你的要求,你需要實際的字符串值存儲在Cells屬性,而不是在OnDrawCell事件有關的動態生成它們:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; 
    Rect: TRect; State: TGridDrawState); 
var 
    Parametertext : string; 
begin 
    Parametertext := StringGrid1.Cells[ACol, ARow]; 
    StringGrid1.Brush.Color := clBtnFace; 
    StringGrid1.Font.Color := clWindowText; 
    StringGrid1.Canvas.FillRect(Rect); 
    DrawText(StringGrid1.Canvas.Handle, PChar(ParameterText), Length(ParameterText), Rect, DT_SINGLELINE); 
end; 

... 

StringGrid1.Cells[0, 0] := 'Test'; 
StringGrid1.Cells[1, 0] := 'Test1'; 

如果你不打算使用Cells屬性要存儲字符串,您最好使用TDrawGrid代替。

+0

感謝@Remy Lebeau ..是否有任何其他方式來獲取由'DrawText'函數生成的單元格值?其實我試圖使用測試完成工具自動化Delphi應用程序。 – bejarun

+0

@bejarun除非您直接鉤住'DrawText()'本身,或使用OCR技術來讀取屏幕上的圖紙,否則不會。 –