2

I want to retrieve a data from database, after modifying the record then I want to show it in Gridview.

I already created column names through Edit columns those names are Date,Location,Job Title,Details.

This is my asp.net code

<asp:GridView ID="GridViewRecord" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField HeaderText="Date" />
                    <asp:BoundField HeaderText="Location" />
                    <asp:BoundField HeaderText="Job Title" />
                    <asp:BoundField HeaderText="Experience" />
                    <asp:HyperLinkField HeaderText="Details" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>

Then I try to add one sample record directly. But I am getting an error. This is my c# code on page load

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();

        DataRow dr = dt.NewRow();
        dr[0] = "12-12-12"; //Error message occured here
        dr[1] = "Jeddah";
        dr[2] = "Java";
        dr[3] = "2";
        dr[4] = "View Details";

        dt.Rows.Add(dr);
        GridViewRecord.DataSource = dt;
        GridViewRecord.DataBind();
    }
}

Error message:

An exception of type 'System.IndexOutOfRangeException' occurred in` System.Data.dll but was not handled in user code
Additional information: Cannot find column 0.

I am new to c#, thanks

naveen
  • 53,448
  • 46
  • 161
  • 251
mohamed faisal
  • 63
  • 1
  • 2
  • 7

3 Answers3

1

You have not added any columns to the DataTable, that's why.

// Create a new DataTable object.
DataTable table = new DataTable();

// Declare a DataColumn
DataColumn column;

// Create the new DataColumn, set DataType, ColumnName and add then add to DataTable.    
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
table.Columns.Add(column);

// I think that the line-by-line explanation is better for the purpose of this answer
// you can of course do all of this in one row, assuming that you already have a datatable
table.Columns.Add("id", typeof(int));

However, in your example you are creating your own DataTable, why aren't you using the one from the Database? That will already have columns that match your select query.

// create DataSet
DataSet ds = new DataSet();

// your operations for filing the DataSet with data from the database which you have not shared
// ...
// ...

// check to see whether we have a DataTable in the DataSet (if the query fails, ds.Tables.Count == 0)
if (ds.Tables.Count > 0) {
   DataRow row = ds.Tables[0].NewRow();
   // add data according to the schema
   // e.g.
   row["id"] = "blah";
   // add the rest of the columns

   // and lastly add the newly created row to the DataTable;
   ds.Tables[0].Rows.Add(row);
}

// now bind
GridViewRecord.DataSource = ds.Tables[0];
GridViewRecord.DataBind();
Ted
  • 3,985
  • 1
  • 20
  • 33
  • You can squish your declaration, constructor call, and property assignments for the column into a single line. And `System.Type.GetType("System.Int32");` should probably avoided in favor of the `typeof` keyword. – mason Sep 20 '16 at 13:30
  • @mason - msdn disagrees with you. I'll go with them. https://msdn.microsoft.com/en-us/library/system.data.datatable.newrow(v=vs.110).aspx – Ted Sep 20 '16 at 13:31
  • Just because they used that that doesn't mean they disagree with me. It just means it was written a long time ago. MSDN documents are full of outdated coding practices. Using `typeof` operator doesn't rely on magic strings. – mason Sep 20 '16 at 13:35
  • @mason - You might be right. However the purpose of my answer is to explain why you cannot add a row with columns to a `DataTable` without columns. – Ted Sep 20 '16 at 13:48
  • Yes, I understand the purpose. I just think it'd be a lot more concise and cleaner if you simply did `DataColumn column = new DataColumn("id", typeof(int));` or even `table.Columns.Add("id", typeof(int));` It's your answer. – mason Sep 20 '16 at 13:55
  • yes it is the correct answer. +1 its simpler to do like this. why type a lot of code. http://stackoverflow.com/a/38521289/17447 – naveen Sep 20 '16 at 13:58
-1

You can also use generic list or list of strings which will make you code simple And also performance wise DataTable is not good as compared to list

Eg:

List<string> lstRecord = new List<string>
{
    "12-12-12",
    "Jeddah",
    "Java",
    "2",
    "View Details"
};
GridViewRecord.DataSource = lstRecord;
GridViewRecord.DataBind();
Imran Sh
  • 1,623
  • 4
  • 27
  • 50
-2
  if (!this.IsPostBack)
            {   DataTable dt = new DataTable();
                dt.Columns.Add("0");
                dt.Columns.Add("1");
                dt.Columns.Add("2");
                dt.Columns.Add("3");
                dt.Columns.Add("4");

                DataRow dr = dt.NewRow();
                dr[0] = "12-12-12"; //Error message occured here
                dr[1] = "Jeddah";
                dr[2] = "Java";
                dr[3] = "2";
                dr[4] = "View Details";

                dt.Rows.Add(dr);
                GridViewRecord.DataSource = dt;
                GridViewRecord.DataBind();
            }

you need add to DataTable columns to working it (0,1,2,3,4) coresponds to table array like you write dr[0]= Add("0");

or you can easly manage to whith column you want insert date you can do

dr["2"]= "Java";  
Taol
  • 1