如何从GridView列中删除/替换子字符串?

时间:2015-10-27 06:27:41

标签: c# asp.net .net gridview

我在GridView下面:

enter image description here

如果存在,我想从日期列中删除0:00:00。我更改了dataformatstring,但也删除了9:09:15

我在auto-generate fields文件上使用DataBind.cs

我尝试了Replace,但无效:

e.Row.Cells[0].Text = e.Row.Cells[0].Text.Replace("0:00:00"," ");

我该怎么做?

的GridView:

<asp:GridView ID="GridView4" runat="server" BackColor="White" 
    BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
    GridLines="Vertical" Width="98%" 
    Height="100%" onrowdatabound="GridView4_RowDataBound" RowStyle-HorizontalAlign="Center" >
    <AlternatingRowStyle BackColor="#DCDCDC" />
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#0000A9" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>

代码:

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            OleDbConnection Connection6;
            using (Connection6 = new OleDbConnection("Provider=MSDAORA.1;Data Source=XXXXXX:1521/orcl;Persist Security Info=True;Password=XXXXXXX;User ID=XXXXXX;"))
            {
            string sqlQuery = "select * from db.user";

            using (OleDbDataAdapter cmd = new OleDbDataAdapter(sqlQuery, Connection6))
            {
                Connection6.Open();
                DataTable dt = new DataTable();
                cmd.Fill(dt);
                GridView4.DataSource = dt;
                GridView4.DataBind();

                Connection6.Close();
            }
        }
    }
        catch (Exception)
        {
        }
    }

1 个答案:

答案 0 :(得分:3)

您可以使用RowDataBound事件,然后使用findcontrol

标记控件
stage.getScene().getRoot()

如果您没有模板字段并使用绑定字段,请使用

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
        onrowdatabound="GridView1_RowDataBound">
  <Columns>    
    <asp:TemplateField HeaderText="Date">
      <ItemTemplate>
         <asp:Label ID="lblDate" Text='<%# Eval("Date") %>' runat="server"></asp:Label>
 .....
 </Columns>
</asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
   {      
    var lbl =  e.Row.FindControl("lblDate") as Label;
    lbl.Text = lbl.Text.Replace("0:00:00", "");     
   }
}