I have a gridview control and I want to input a value to a textbox and click button so that it inserts a value from textbox.text to the gridview. I use this code:
<asp:TextBox ID="txtName" runat="server" ViewStateMode="Enabled"></asp:TextBox>
<br />
<asp:Button ID="btnAddName" runat="server" Text="Button"
onclick="btnAddName_Click" />
<br />
<br />
<asp:GridView ID="gvName" runat="server" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and:
protected void btnAddName_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("lblName", typeof(string)));
DataRow _dr = dt.NewRow();
_dr["lblName"] = txtName.Text;
dt.Rows.Add(_dr);
gvName.DataSource = dt;
gvName.DataBind();
}
I input the text in the textbox and click on the button to insert a value to the gridview. It works ok, but on the second step, after page postback it lost previous data in the gridview.
I want to not lose the previous data in the gridview. Please help me.
You need to add row to original source you are binding to GridView. if you create new table each time you click button and bind that to gridview, it will show data from new DataTable and old data.
try this
protected void btnAddName_Click(object sender, EventArgs e)
{
DataTable dt;
if(Session["dt"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("lblName", typeof(string)));
}
else
{
dt = (DataTable)Session["dt"];
}
DataRow _dr = dt.NewRow();
_dr["lblName"] = txtName.Text;
dt.Rows.Add(_dr);
gvName.DataSource = dt;
gvName.DataBind();
Session["dt"] = dt;
//store dt in session so that you can reuse it again after postback
}
Are you checking in your Page_Load Method if your page is in PostBack mode?
if(IsPostBack) { //Load the data for the first time }
If not, your originally and "old" data will be bind to the gridview.
Update:
To reuse the old data, store the datatable in a session variable, load it from there, add the new line and bind data datatable again.
Related
I have a DataGridView with a column which with button.
Now I want that with every click on the button the selected row in the DataGridView is copied and inserted directly after the selected row.
I want to duplicate all value of all columns and insert into table of my database this new row.
How can I realize this ?
Many thanks in advance.
On my code below the error is on this line
cgv.Rows.Add(gvRow.Cells[1].Text);
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="btselect" runat="server"
CommandName="Select"
OnClick="Copy"
ImageUrl="/aspnet/img/clone_icon.gif"
ToolTip="Clone row" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerId" HeaderText="ID" />
</Columns>
</asp:GridView>
protected void Copy(object sender, EventArgs e)
{
GridViewRow gvRow = this.gvProducts.SelectedRow;
DataTable cgv = null;
if (ViewState["Customers"] != null)
{
cgv = ViewState["Customers"] as DataTable;
cgv.Rows.Add(gvRow.Cells[1].Text);
ViewState["Customers"] = cgv;
}
BindData();
}
protected void gvProducts_SelectedIndexChanged(object sender, EventArgs e)
{
this.gvProducts.SelectedRow.BackColor = System.Drawing.Color.Cyan;
}
Ok, you are in a good place in that you attempting to add the data row to the data source, or the datatable that you are persiting in session.
So, I would do it this way:
protected void Copy(object sender, EventArgs e)
{
GridViewRow gvRow = this.gvProducts.SelectedRow;
DataTable cgv = null;
if (ViewState["Customers"] != null)
{
cgv = ViewState["Customers"] as DataTable;
DataRow MyNewRow = cgv.NewRow()
MyNewRow["FirstName"] = gvRow.Cells[2].Text;
MyNewRow["LastName"] = gvRow.Cells[3].Text;
MyNewRow["CustomerID"] = gvRow.Cells[0];
cgv.Rows.Add(MyNewRow);
ViewState["Customers"] = cgv;
}
BindData();
}
Do remember that any template field in the GV needs to use find control, but from what you posted, it does look like using .cells[] collection should work for you.
i want to add textBox into dataTable row.I dont know how to do that.Is it possible to add textBox to a dataTable?First it give me this error:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
Here is my code:
Markup:
<asp:GridView ID="GridView2" runat="server" ShowHeader="false" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<ItemTemplate >
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
private void AddNewRecordRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr;
dt.TableName = "table";
dt.Columns.Add(new DataColumn("Zabeleshka", typeof(TextBox)));
dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["marks"] = dt;
if (ViewState["marks"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["marks"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
drCurrentRow["Zabeleshka"] = TextBox1.Text;
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["marks"] = dtCurrentTable;
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
}
You can add a textbox into a gridview no problem then find it from the code behind in the RowDataBound Grid Method. Your problem is more than likely the fact that you have closed your TemplateField and have not opened one. You need to add
<asp:TemplateField>
above your
<ItemTemplate>.
As your markup code i think you want Text Box inside Gridview with containing some value into that,
for this,
first of all your markup is not correct, the correct one is,
<asp:GridView ID="GridView2" runat="server" ShowHeader="false" OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField> <%-- you have not opened it in your markup --%>
<ItemTemplate >
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind,
to get the textbox value you need
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
edited,
in your code,
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBox1 = (TextBox)GridView2.Rows[0].FindControl("TextBox1");
drCurrentRow["Zabeleshka"] = TextBox1.Text;
the for loop condition is (i <= dtCurrentTable.Rows.Count)
you should try this (i < dtCurrentTable.Rows.Count)
because the counting of row is start from 0 and thats why you getting index out of range error.
i have grid view which have two drop down list. so user can change drop down list value at run time. here is my grid view design code :
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<HeaderTemplate>
<asp:LinkButton ID="lbut_sortstatus1" runat="server"
CommandArgument="status_id" CommandName="Sort" CssClass="normaltext"
Font-Bold="true" Text="Status"></asp:LinkButton>
<asp:PlaceHolder ID="placeholderstatus1" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDL_StatusList1" runat="server"
DataTextField="status_name" DataValueField="Id" AppendDataBoundItems="true"
AutoPostBack="True"
onselectedindexchanged="DDL_StatusList1_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="DDL_StatusList1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
how ever this is my Page_Load code :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Status();
Bind_DDL_Group();
Bind_DDL_Countries();
}
this.GetData();
}
and here is my one of drop down list bind method that shows how i binding grid view drop down list.
public void Bind_DDL_Group()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Groups.Select(g=>g).OrderBy(g=>g.Group_name).ToList();
DataSet myDataset = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Group_name", typeof(string));
foreach (var item in query)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Group_name"] = item.Group_name.ToString();
dt.Rows.Add(dr);
}
myDataset.Tables.Add(dt);
DDL_GroupList.DataSource = myDataset;
DDL_GroupList.DataBind();
DropDownList bind_dropdownlist;
foreach (GridViewRow grdRow in GV_ViewUserList.Rows)
{
bind_dropdownlist = (DropDownList)(GV_ViewUserList.Rows[grdRow.RowIndex].Cells[8].FindControl("DDL_GroupList1"));
bind_dropdownlist.DataSource = myDataset;
bind_dropdownlist.DataBind();
}
}
}
however at Page load first time it's works successfully but when user clicks sorting or pagging then drop down list get empty. how ever i binds them in (!Page.IsPostBack) of Page_Load.
what I'm doing wrong here..
please help me...
Please put dropdown binding code out of if(!Page.IsPostBack) condition
Because when go to another page in gridview Page will be posted back to server
and if(!Page.IsPostBack) condition will return false.
Change your code to
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Countries();
}
Bind_DDL_Status();
Bind_DDL_Group();
this.GetData();
I a newbie to asp.net. I have created a DB table in sqlserver with 3 columns; ImageID, Filename & Score.
FileName is C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg.
Using C# asp.net, I have created a GridView. This Gridview should populate
(column 1)ImageID and get the image from the Filename (column2) and I have 2 Checkboxlist created as shown below which should accept score for the images from user and save it into the DB table.
Question 1 .
I am able to populate Image ID, but Images are not getting populated.
Question 2.
I do not know how to access the checkboxlist since it is in template. The checked is in the default select and doesn't change even if I click on it. Which method/property should be used to do save the selection to the database. Here's my code
<form id="form1" runat="server">
<p style="height: 391px">
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:CheckBoxList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test">
<asp:ListItem Selected="True" Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" Width="130px" />
<asp:Button ID="Button2" runat="server" OnClientClick="javaScript:window.close(); return false;" Text="Exit" Width="102px" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
</form>
public string sqlSel = #"SELECT TOP 3 [ImageID],FileName FROM [db1].[ImagesTest] where [Score] is null";
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmdSel = new SqlCommand(sqlSel, connection);
SqlDataReader reader1 = cmdSel.ExecuteReader();
while (reader1.Read())
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
}
private DataSet GetData(string cmdSel)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter(cmdSel,con);
sda.Fill(ds);
}
catch (Exception ex)
{
Response.Write("IN EXCEPTION "+ex.Message);
return null;
}
return ds;
}
Thanks for ur time
Rashmi
There are several issues with your code, here is what it should be fixed:
How to fix the images (Question 1)
As #Guilherme said in the comments, for images use URLs instead of disk paths.
Replace the images disk paths C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg to something like Images/beads.png and Images/scenary.jpeg.
For this to work, you will need to have a folder named Images that contains these two files on the same directory level as your .aspx file.
Adjust your GridView1 declaration in the ASPX file
On your GridView1 declaration you should:
attach a handler to the OnRowDataBound event. This will allow you to properly bind the Score dataset column to the Score gridview column
set the DataKeyNames property on the grid to what should be the primary key for your images table (in this case DataKeyNames="ImageID")
use a RadioButtonList instead of a CheckboxList, because according to your dataset you can only set one value, which is what the RadioButtonList does. The CheckboxList is normally used when multiple selection is needed.
attach a handler to the SelectedIndexChanged event on the RadioButtonList. This will allow you to save the new values to the database (Question 2)
Here's how your GridView declaration should look like:
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ImageID">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="RadioButtonList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:RadioButtonList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged">
<asp:ListItem Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:RadioButtonList>
<!-- UPDATED! - keep the old values in a hidden field -->
<asp:HiddenField runat="server" ID="hfOldScore" Value='<%# Eval("Score") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Adjust your code behind value in your .ASPX.CS file (Question 2)
On the code behind, you will also need to:
Make sure you are binding to the GridView only once in the Page_Load event, by checking the IsPostBack property
(Optional, but recommended) Move the logic of getting data (with the SQLConnection code) in a separate method that will handle only data retrieval
Implement the handler for the OnRowDataBound event. This will bind any values from the Score column to the RadioButtonList control
Implement the handler for the SelectedIndexChecked event of the RadioButtonList control. This will allow you to save to the database the new values
Finally, here's the entire code-behind code:
protected void Page_Load(object sender, EventArgs e)
{
//bind only the first time the page loads
if (!IsPostBack)
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
private DataSet GetData(string cmdSel)
{
//normally you should query the data from the DB
//I've manually constructed a DataSet for simplification purposes
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
dt.Columns.Add(new DataColumn("FileName", typeof(string)));
dt.Columns.Add(new DataColumn("Score", typeof(int)));
dt.Rows.Add(100, #"Images/beads.png", 0);
dt.Rows.Add(200, #"Images/moreimages/scenary.jpeg", 3);
dt.Rows.Add(300, #"Images/moreimages/scenary.jpeg", 5);
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
//UPDATED - iterate through all the data rows and build a dictionary of items
//to be saved
Dictionary<int, int> dataToUpdate = new Dictionary<int, int>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int imageID = (int)GridView1.DataKeys[row.RowIndex].Value;
int oldScore;
int newScore;
int.TryParse((row.FindControl("hfOldScore") as HiddenField).Value, out oldScore);
int.TryParse((row.FindControl("test") as RadioButtonList).SelectedValue, out newScore);
if (oldScore != newScore)
{
dataToUpdate.Add(imageID, newScore);
}
}
}
//update only the images that were changed
foreach (var keyValuePair in dataToUpdate)
{
SaveToDB(keyValuePair.Key, keyValuePair.Value);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//we are only interested in the data Rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dataRow = (e.Row.DataItem as DataRowView).Row;
//manually bind the Score column to the RadioButtonlist
int? scoreId = dataRow["Score"] == DBNull.Value ? (int?)null : (int)dataRow["Score"];
if (scoreId.HasValue)
{
RadioButtonList test = e.Row.FindControl("test") as RadioButtonList;
test.ClearSelection();
test.SelectedValue = scoreId.Value.ToString();
}
}
}
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList test = sender as RadioButtonList;
GridViewRow gridRow = test.NamingContainer as GridViewRow;
//obtain the current image Id
int imageId = (int)GridView1.DataKeys[gridRow.RowIndex].Value;
//obtain the current selection (we will take the first selected checkbox
int selectedValue = int.Parse(test.SelectedValue);
//UPDATED! - saves are now handled on the Save button click
//SaveToDB(imageId, selectedValue);
}
private void SaveToDB(int imageId, int score)
{
//UPDATED!
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.Parameters.Add("#ImageID", imageId);
command.Parameters.Add("#Score", score);
command.CommandText = #"update [db1].[ImagesTest] set Score = #Score where [ImageID] = #ImageID";
command.ExecuteNonQuery();
}
}
}
UPDATED!
The declaration of the GridView1 now contains a hidden field containing the Score value. You can use this hidden field to determine which row has changed, so you can trigger a save only on the changed ones
Save is now done on the click of the Save button, by iterating through the rows of the grid an building a Dictionary<int,string> to keep only the changes.
SaveToDB method should work, but I cannot test this myself.
Question 2:
To access your checkbox you can use.
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("test");
For Question 1
Instead of ImageField you can use use ASP:Image in Templatefield like this
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:Image ID="imageControl" runat="server" ImageUrl='<%# Eval("Filename") %>'></asp:Image>
</ItemTemplate>
</asp:TemplateField>
For Question 2
This is one of the example for how to access each Checkbox list inside gridview
For Each gvr As GridViewRow In Gridview1.Rows
If (CType(gvr.FindControl("CheckBox1"), CheckBox)).Checked = True Then
ReDim uPrimaryid(iCount)
uPrimaryid(iCount) = New Integer
uPrimaryid(iCount) = gvr.Cells("uPrimaryID").Text
iCount += 1
End If
Next
Code behind:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Rego No", typeof(string)));
foreach (var item in list)
{
dt.Columns.Add(new DataColumn(string.Format("{0:dd/MM}",item),typeof(string)));
//enter code here
}
dlcalender.DataSource = dt;
dlcalender.DataBind();
ASPX:
DataTable columns are dynamic like dates. I am binding the DataTable but nothing is showing.
Can you please guide me how to show the header list in DataTable?
with linq.
dlcalender.DataSource = dt.select(p=>new{
c1=p.columns[0],
c2=p.columns[1],
......
});
and use
<%# Eval("c1") %>
<%# Eval("c2") %>
......
The problem is that you've created columns but you haven't inserted any rows in the DataTable so that's why you don't see any results when running the site in your browser
I think you should also understand how the DataList control works in ASP.NET.
You need to create a HeaderTemplate for the information which will only appear once and an ItemTemplate for the items which are going to repeat.
You cannot bind your DataTable to the HeaderTemplate, because it doesn't know which row to use for the headings;
In the example below I've used string properties for headings and your DataTable for the repeating items:
ASPX:
<asp:DataList ID="dlcalender" runat="server">
<FooterTemplate>
</FooterTemplate>
<HeaderTemplate>
<asp:Label ID="head1" runat="server" Text='<%# Heading1 %>' />
<asp:Label ID="head2" runat="server" Text='<%# Heading2 %>' />
<asp:Label ID="head3" runat="server" Text='<%# Heading3 %>' />
<asp:Label ID="head4" runat="server" Text='<%# Heading4 %>' />
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"Rego No")%>
<%# DataBinder.Eval(Container.DataItem,"Column1") %>
<%# DataBinder.Eval(Container.DataItem,"Column2")%>
<%# DataBinder.Eval(Container.DataItem,"Column3")%>
</ItemTemplate>
</asp:DataList>
Code behind:
public string Heading1 { get; set; }
public string Heading2 { get; set; }
public string Heading3 { get; set; }
public string Heading4 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Heading1 = "Heading 1";
Heading2 = "Heading 2";
Heading3 = "Heading 3";
Heading4 = "Heading 4";
var list = new List<string> { "Column1", "Column2", "Column3" };
var table = new DataTable();
table.Columns.Add(new DataColumn("Rego No", typeof(string)));
foreach (var item in list)
table.Columns.Add(item, typeof(string));
//Now add some rows(which will be repeated in the ItemTemplate)
table.Rows.Add("0", "Row 0", "Row 0", "Row 0");
table.Rows.Add("1", "Row 1", "Row 1", "Row 1");
table.Rows.Add("2", "Row 2", "Row 2", "Row 2");
dlcalender.DataSource = table;
dlcalender.DataBind();
}
Also why don't you just use a grid view?It's much better for displaying tabular data, which I believe is what you have
Since you created the data columns dynamically at runtime, you have to add them to the gridview at runtime as well, ex:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Rego No", typeof(string)));
foreach (var item in list)
{
dt.Columns.Add(new DataColumn(string.Format("{0:dd/MM}",item),typeof(string)));
//enter code here
dlcalender.Columns.Add(string.Format("{0:dd/MM}",item), string.Format("{0:dd/MM}",item));
}
dlcalender.DataSource = dt;
dlcalender.DataBind();
In the above code, I have added the column to the datalist in teh same time it is added to the data table.
You can filter them if you don't want to add all of it.