在我的 Web 應用程式中,我有一個 gridview,其中包含來自資料庫的資料。它看起來像這樣:
| 數字 | 地方 |
|---|---|
| 1234579 | 家2 |
| 1787543 | 首頁1 |
我想編輯第一列 ( number) 來格式化 - 右側的第五個字符加粗,右側的三個字符也加粗。
| 數字 | 地方 |
|---|---|
| 12 3 4 579 | 家2 |
| 17 8 7 543 | 首頁1 |
我怎樣才能做到這一點?我在視覺作業室作業,它可以在設計模式或源中設定,或如何設定。謝謝
uj5u.com熱心網友回復:
您可以使用TemplateField將資料移動到代碼后面并根據需要在那里格式化 - 因為在這里您必須拆分您的號碼然后重新格式化它。
所以在GridView里面添加一個 <asp:TemplateField>
<Columns>
<asp:TemplateField HeaderText="number" >
<ItemTemplate>
<%#RenderLine(Container.DataItem)%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
并在后面的代碼上做你的格式..
protected string RenderLine(object oItem)
{
var yourNumber = oItem.ToString();
// split yourNumber, then reformat it using <b> etc... and return it
// need to do some work here, here is an example
var newNumberFormat = string.Format("<b>{0}</b>", yourNumber);
return newNumberFormat;
}
uj5u.com熱心網友回復:
好吧,假設源是某種資料庫,因此最重要的是您必須提取該資料并使用代碼對其進行格式化。
我的意思是,使整個列加粗是微不足道的。但是這里的請求有點麻煩。
好的,所以我們在表中說了這些資料:

我們的標記是這樣的:
<asp:GridView ID="GridView1" runat="server" CssClass="table"></asp:GridView>
好的,我們加載網格的代碼是這樣的:
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT SNumber, Place from tblJunk", conn))
{
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
我們現在有了這個:

現在,作為“通用”規則,格式化網格/串列視圖等,我們可以嘗試將訊息服務器運算式注入到標記中,但是為了設定顏色、突出顯示和格式化,最好使用該控制元件的資料系結事件。
所以,我們可以有這樣的代碼:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string txt = e.Row.Cells[0].Text;
// bold 5th from right
int rPos = txt.Length - 4;
txt = MyBold(txt, rPos, 1);
// bol last 3 chars
rPos = txt.Length - 2;
txt = MyBold(txt, rPos, 3);
e.Row.Cells[0].Text = txt;
}
}
現在我們的輸出是這樣的:

所以,為了改變狀態和格式化網格(比如狀態的顏色等),上面是一般的方法。
當然,我們需要一些名為 MyBold 的函式。
像這樣說:
string MyBold(string s,int iStart, int iEnd)
{
// ONE based postions - NOT 0 based!
iStart -= 1;
s = rLeft(s, iStart) "<strong>" s.Substring(iStart, iEnd) "</strong>"
s.Substring(iStart iEnd, s.Length - (iStart iEnd));
return s;
}
string rLeft(string s,int r)
{
return s.Substring(0, r);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322391.html
