0

I am a beginner in asp.net and c#. I want to bind image and name to gridview without any database by hardcoding them in code behind. I tried like below but these values are not binded to Gridview1. Can anyone tell me where it goes wrong?

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>  
            <asp:BoundField DataField="Profile_Name" HeaderText="Profile_Name" />  
            <asp:BoundField DataField="ImageUrl" HeaderText="ImageUrl" />  
</Columns>  

protected GridView GridView1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.loadTable();
    }
}
private void loadTable()
{
    DataSet ds = new DataSet();
    DataTable dt;
    DataRow dr;
    DataColumn pName;
    DataColumn pImage;

    dt = new DataTable();
    pName = new DataColumn("Profile_Name", Type.GetType("System.String"));
    pImage= new DataColumn("ImageURL", Type.GetType("System.String"));

    dt.Columns.Add(pName);
    dt.Columns.Add(pImage);

    dr = dt.NewRow();
    dr["Profile_Name"] = "John Cena";
    dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Friends-PNG-Photos.png";

    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["Profile_Name"] = "Hannah Ray";
    dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Image.png";

    dt.Rows.Add(dr);
    ds.Tables.Add(dt);

    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
}
  • 2
    You can create a model class and use `List` or other collections (e.g. `List`) if you're not want to bind from database. Here is an example for getting started: https://stackoverflow.com/questions/5517676/how-do-i-bind-a-gridview-to-a-custom-object. – Tetsuya Yamamoto Nov 06 '17 at 04:03
  • What have you tried so far? Post some code for help – Ipsit Gaur Nov 06 '17 at 04:03
  • I have edited my question with what I had followed earlier. I m not sure what goes wrong in this. – buddingengineer Nov 06 '17 at 12:49

2 Answers2

4

In the background you can make a new DataTable:

DataTable dt = new DataTable();

Then you can add data columns and rows through the dt.Rows and dt.Columns methods, and then set:

DataGridView.ItemsSource = dt.defaultview;

Hope that you find this helpful.

Leopold Joy
  • 4,524
  • 4
  • 28
  • 37
  • Thank you so much! I have edited my question with what I had followed earlier. I m not sure what goes wrong in this. Can you please point out? – buddingengineer Nov 06 '17 at 12:58
0

You can bind all objects to a DataGrid:

datagrid.DataSource = object;
datagrid.DataBind();
Wyck
  • 10,311
  • 6
  • 39
  • 60
  • Thanks @buraq enigma. I have edited my question with what I had followed earlier. I m not sure what goes wrong in this. Can you please point out? – buddingengineer Nov 06 '17 at 13:12