Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add gridview with objectdatasource in code behind c#?

Tags:

c#

asp.net

I want to create gridview with code. My code is:

 GridView gdvList = new GridView();
 gdvList.ID = "gdvList" ;
 TemplateField tField = new TemplateField();
 BoundField dateBF = new BoundField();
 dateBF.DataField = "Date";
 gdvList.Columns.Add(dateBF);
 BoundField countResponse = new BoundField();
 countResponse.DataField = "CountResponse";
 gdvList.Columns.Add(countResponse);
 ObjectDataSource ods = new ObjectDataSource();
 ods.ID = "ods";
 ods.TypeName = "Project.BLLQuestion";
 ods.SelectMethod = "GetByGroupID";
 ods.SelectParameters["GroupID"] = new Parameter("inGroupID", DbType.Int32, "0");
 ods.DataBind();
 gdvList.DataSource = ods;
 gdvList.DataBind();    

this code does not work, and how to add TemplateField do :

<asp:TemplateField ItemStyle-CssClass="GridItemTemplateField">
    <ItemTemplate>
         <a href="Question.aspx?id=<%# Eval("ID")%>"><%# Eval("Content").ToString().PadRight(140).Substring(0,140).TrimEnd()+"..." %></a>
    </ItemTemplate>
</asp:TemplateField>

how can do it?

like image 317
shahroz Avatar asked Dec 23 '15 05:12

shahroz


1 Answers

  1. You need to set DataSourceID property of Grid, not DataSource.
  2. There are no need to run DataBind() method of ObjectDataSource.
  3. Ensure that both controls ObjectDataSource and GridView are added on Page.

Try this:

  ObjectDataSource ods = new ObjectDataSource();
  ods.ID = "ods";
  ods.TypeName = "Project.BLLQuestion";
  ods.SelectMethod = "GetByGroupID";
  ods.SelectParameters["GroupID"] = new Parameter("inGroupID", DbType.Int32, "0");

  Page.Controls.Add(ods);

  GridView gdvList = new GridView();
  gdvList.ID = "gdvList" ;
  gdvList.DataSourceID = "ods";

  BoundField dateBF = new BoundField();
  dateBF.DataField = "Date";
  gdvList.Columns.Add(dateBF);

  BoundField countResponse = new BoundField();
  countResponse.DataField = "CountResponse";
  gdvList.Columns.Add(countResponse);

  Page.Controls.Add(gdvList);

  gdvList.DataBind(); 

According to your second question. Try to replace TemplateField by HyperLinkField. Click here for details.

like image 77
Pavel Timoshenko Avatar answered Sep 18 '22 20:09

Pavel Timoshenko