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.
Related
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 two GridView and i want display data from two DataTables. There is my GridViews code in aspx file :
<div class="col-sm-5">
<div class="col-sm-6">
<asp:GridView ID="gvSource" runat="server" ShowHeaderWhenEmpty="true" CssClass="drag_drop_grid GridSrc" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (wybór)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="col-sm-6 pull-left">
<asp:GridView ID="gvDest" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No data to display" CssClass="drag_drop_grid GridDest" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Miejsca (należące do wycieczki)</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNazwa" runat="server" Text='<%# Eval("Nazwa") %>' />
<asp:HiddenField ID="IDVal" ClientIDMode="Static" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
There is my Code-Behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
recID = int.Parse(Request.QueryString["id"]);
if (recID > 0)
{
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
dt2.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Nazwa", typeof(string)) });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
dt.Rows.Add(lst.Id , lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
Wycieczka w = (new Wycieczki()).PobierzWycieczke(recID);
foreach (var lst in w.Miejsca)
{
Miejsce tempM = (new Miejsca()).PobierzMiejsce(lst.Id_Miejsce.Id);
dt2.Rows.Add(tempM.Id, tempM.Nazwa);
}
int ilosc = dt2.Rows.Count;
//gvDest.UseAccessibleHeader = true;
gvDest.DataSource = dt2;
gvDest.DataBind();
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "TablicaMiejsc", "loadPlacesIntoTrip("+recID+");", true);
}
}
else
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Nazwa") });
Miejsca ms = new Miejsca();
Hashtable hs = new Hashtable();
foreach (var lst in ms.PobierzMiejscaLista(hs))
{
//listMiejsc.Add(lst);
dt.Rows.Add(lst.Id, lst.Nazwa);
}
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
gvDest.DataSource = new List<String>();
gvDest.DataBind();
recID = 0;
}
}
}
And i don't know why but only one GridView (gvSource) display data.
Second GridView (gvDest) not display data.
When i debug code i see both DataTables have data. Both GridView DataSources have data too. But only one GridView display data.
I use Nhibernate to lazy load (w.Miejsca) collection and get objects like "Miejsce" or "Wycieczka" from database. Also I use JQuery and JQuery UI to make sortable GridViews.
Sorry for my bad english, it's not my native language.
I hope you can help me :)
UPDATE
Finally I found what is responsible for this situation.
Because of my stupidity i lost a lot of time :)
This line of code is removed the items from GridView:
$("[id*=gvDest] tr:not(tr:first-child)").remove();
Thank you for your advice.
The problem was solved.
Please remove ClientIDMode="Static" from second grid view and check it.
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
I am trying to manipulate a DropDownList, which is in a field of a GridView, from code-behind in ASP.NET. I am doing this by adding the reference to a local DDL with the FindControl method. However, it doesn't seem to work, I have tried multiple approaches (Load, Init Events) but I always get a NullReferenceException.
Here is my code:
<asp:TemplateField HeaderText="Zuständige Führungskraft">
<ItemTemplate>
<!-- <%# Eval("ZustaendigeFuehrungskraft")%> -->
<asp:DropDownList AppendDataBoundItems="true" Enabled="false" runat="server" ID="ddwnFK" >
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList AppendDataBoundItems="true" runat="server" ID="ddwnFK" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
protected void grdBenutzer_RowEditing(object sender, GridViewEditEventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT Nachname, Vorname FROM Benutzer WHERE Benutzerart='Führungskraft' AND Archiviert != 1", conn);
SqlDataReader dr = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(dr);
foreach (GridViewRow row in grdBenutzer.Rows)
{
DropDownList ddwnFK = (DropDownList)row.FindControl("ddwnFK");
//if (ddwnFK == null)
// continue;
ddwnFK.Items.Add("keine");
foreach (DataRow dtRow in table.Rows)
{
ddwnFK.Items.Add(dtRow["Nachname"].ToString() + ", " + dtRow["Vorname"].ToString());
}
}
}
can you try access it as
DropDownList ddwnFK = (DropDownList)row.Cells[0].Controls[0];
or see in the Quick watch what are the contents of row there.
It seems you're trying to find your drop down in every row of your grid (even header/footer row doesn't contain your drop down).
You can access the row being edited by using GridViewEditEventArgs.NewEditIndex property:
var row = grdBenutzer.Rows[e.NewEditIndex];
var ddwnFK = (DropDownList)row.FindControl("ddwnFK");
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.