c# - ASP.NET 设置 GridView 中 DataBound 列的宽度

标签 c# asp.net gridview

我有一个 GridView,它使用 BoundField 作为列。我正在尝试为我的 UserInfo 列设置一个最大宽度。

我试过很多方法,但没有一个奏效。下面是我的 GridView 的代码:

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId"></asp:BoundField>

                <asp:BoundField HeaderText="Username" 
                DataField="Username" 
                SortExpression="Username"></asp:BoundField>

                <asp:BoundField HeaderText="UserInfo" 
                DataField="UserInfo" 
                SortExpression="UserInfo"></asp:BoundField>

                </Columns>
</asp:GridView>

寻找有关如何设置特定列宽度的建议,该列是我的 UserInfo 列。

最佳答案

我为您做了一个小演示。演示如何显示长文本。

在这个例子中有一个名称列,它可能包含很长的文本。 boundField 将显示表格单元格中的所有内容,因此单元格将根据需要扩展(因为内容)

TemplateField 也将呈现为单元格,但它包含一个 div,它限制 宽度任何内容,例如 40px。所以这一列将有某种最大宽度!

    <asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
        <Columns>
            <asp:BoundField HeaderText="ID" DataField="ID" />
            <asp:BoundField HeaderText="Name (long)" DataField="Name">
                <ItemStyle Width="40px"></ItemStyle>
            </asp:BoundField>
            <asp:TemplateField HeaderText="Name (short)">
                <ItemTemplate>
                    <div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
                        <%# Eval("Name") %>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

enter image description here

下面是我的演示代码

 public partial class gridViewLongText : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         #region init and bind data
         List<Person> list = new List<Person>();
         list.Add(new Person(1, "Sam"));
         list.Add(new Person(2, "Max"));
         list.Add(new Person(3, "Dave"));
         list.Add(new Person(4, "TabularasaVeryLongName"));
         gvPersons.DataSource = list;
         gvPersons.DataBind();
         #endregion
     }
 }

 public class Person
 {
     public int ID { get; set; }
     public string Name { get; set; }

     public Person(int _ID, string _Name)
     {
         ID = _ID;
         Name = _Name;
     }
 }

关于c# - ASP.NET 设置 GridView 中 DataBound 列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8266580/

相关文章:

c# - 反序列化使得字段是一个空列表而不是 null

jquery - 使用 jquery ajax ASP.NET MVC 填充下拉列表

c# - 如何将gridview中选中的行保存到sql数据库

c# - RabbitMQ服务器认为它已经发送了消息,RabbitMQ客户端不同意

c# - 当申请人等于资源时的公平彩票

asp.net - 将数据表绑定(bind)到 GridView

asp.net - ASP.Net Core MVC 中的 OutputCache

c# - asp.net gridview动态绑定(bind)

javascript - 使用 MixItUp jquery 插件从 GridView 切换到 ListView

c# - 卡巴斯基将我的 ConsoleApplication 检测为木马