I want to add a new blank row to the gridview after binding as seen in the picture when clicking the link button below. The textboxes inside the gridview should remain the same if there is any data entered in it. I just want to add one row.
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
You can run this example directly.
aspx page:
<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
<ItemTemplate>
<asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
<ItemTemplate>
<asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grd.DataSource = GetTableWithInitialData(); // get first initial data
grd.DataBind();
}
}
public DataTable GetTableWithInitialData() // this might be your sp for select
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
table.Rows.Add(1, "David", "1");
table.Rows.Add(2, "Sam", "2");
table.Rows.Add(3, "Christoff", "1.5");
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get select column header only records not required
DataRow dr;
foreach (GridViewRow gvr in grd.Rows)
{
dr = dt.NewRow();
TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
dr[0] = txtPayScale.Text;
dr[1] = txtIncrementAmount.Text;
dr[2] = txtPeriod.Text;
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add last empty row
dt.Rows.Add(dr);
grd.DataSource = dt; // bind new datatable to grid
grd.DataBind();
}
public DataTable GetTableWithNoData() // returns only structure if the select columns
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
return table;
}
protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
{
GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = " ";
gvRow.Cells.Add(tCell);
Table tbl = e.Row.Parent as Table;
tbl.Rows.Add(gvRow);
}
}
}
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:
adapter.Fill(ds);
ds.Tables(0).Rows.Add();
Related
I'm getting this error whenever I try to bind data inside gridview dropdownlist.
Here is the aspx code:
<asp:TemplateField HeaderText="Item Description" SortExpression="ddlItem">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind (c#):
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("lblId");
tempDataTable.Columns.Add("ddlItem");
tempDataTable.Columns.Add("txtUnit");
tempDataTable.Columns.Add("txtQty");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempDataTable;
gvItemList.DataBind(); //Here I'm getting the error.
}
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
Jilu1TableAdapters.tbl_ItemTableAdapter item;
item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItems();
ddlItem.DataSource = dt;
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
DataTable dt = new DataTable();
dt = ds.GetVersion(ddlSiteID.SelectedValue);
ddlVersion.DataSource = dt;
ddlVersion.DataValueField = "Version";
ddlVersion.DataTextField = "Version";
ddlVersion.DataBind();
int ver = Convert.ToInt32(ddlVersion.Text);
DataTable dt1 = new DataTable();
dt1 = ds.GetDetails(ddlSiteID.SelectedValue, ver);
foreach (DataRow row in dt1.Rows)
{
txtSiteName.Text = (row["txtSiteName"].ToString());
ddlSiteType.Text = (row["ddlSiteType"].ToString());
txtNoBTS.Text = (row["txtNoBTS"].ToString());
txtNoLinks.Text = (row["txtNoLinks"].ToString());
txtLoadBand.Text = (row["txtLoadBand"].ToString());
ddlEBAvailability.Text = (row["ddlEBAvailability"].ToString());
txtEBPhase.Text = (row["txtEBPhase"].ToString());
txtDGCapacity.Text = (row["txtDGCapacity"].ToString());
txtDGPhase.Text = (row["txtDGPhase"].ToString());
}
gvItemList.DataSource = dt1;
gvItemList.DataBind();
}
I tried putting Text = 'Bind("ddlItem")', Datasourse, SelectedValue but still no luck.
Any help will be greatly appreciated.
In this code ,
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px"
SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
you set SelectedValue to '<%# Eval("ddlItem") %>' but ddlItem is not exist in your datasource fields .
Put the correct field which you want to display in your dropdownlist .
And I suggest you to set DataTextField and DataValueField of your DropDownList .
Set it like DataTextField="ddlItem" DataValueField="ddlItem" .
Hope it's help for you :)
Your way is wrong
try this below way
protected void gvItemList_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlItem");
//bind dropdownlist
DataTable dt = con.GetData("select * from tablename");//selected data from db or anywhere for bind ddl
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";//id
ddList.DataValueField = "YourCOLName";//displaying name
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["YourCOLName"].ToString();// default selected value
}
}
}
My Code successfully adds new rows to the gridview on the button click, but clears all entered values in existing rows. I understand that, the existing data should be stored into a ViewState, but I do not know where/how to achieve this.
ASPX:
<asp:GridView ID="gvCommissions" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" AutoGenerateDeleteButton="True">
<Columns>
<asp:TemplateField HeaderText="S.NO" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="lblSno" runat="server" Width="98%"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME" ItemStyle-Width="30%">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="98%"></asp:TextBox>
</ItemTemplate>
</Columns>
</asp:GridView>
CODE BEHIND:
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["gvCommissions"] != null)
dt = (DataTable)ViewState["gvCommissions"];
if (!Page.IsPostBack)
{
GridViewStructure();
AddNewRow();
}
else
{
dt = (DataTable)ViewState["gvCommissions"];
}
ViewState["gvCommissions"] = dt;
}
private void GridViewStructure()
{
dt = new DataTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
}
private void AddNewRow()
{
dt = new DataTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
foreach (GridViewRow gvRow in gvCommissions.Rows)
{
DataRow drCurrentRow = dt.NewRow();
drCurrentRow["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;
drCurrentRow["name"] = ((TextBox)gvRow.FindControl("txtName")).Text;
dt.Rows.Add(drCurrentRow);
}
DataRow dr = dt.NewRow();
dr["sno"] = "";
dr["name"] = "";
dt.Rows.Add(dr);
gvCommissions.DataSource = dt;
gvCommissions.DataBind();
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
Its Simple first check if there is any row in gridview then add rows value in datatable then add the empty row. As below.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
AddNewRow();
}
}
private void AddNewRow()
{
DataTable dt = new DatatTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
foreach (GridViewRow gvRow in gvCommissions.Rows)
{
DataRow dr = dt.NewRow();
dr["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;
dr["name"] = ((Label)gvRow.FindControl("txtName")).Text;
dt.Rows.Add(dr);
}
DataRow dr1 = dt.NewRow();
dr1["sno"] = "";
dr1["name"] = "";
dt.Rows.Add(dr1);
gvCommissions.DataSource = dt;
gvCommissions.DataBind();
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
You missed one part. Each time the page is loaded, you are saving the table to view state, and forgot to use it!
Try to retrieve it from viewstate at page load like this:
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["gvCommissions"] != null) dt = (DataTable)ViewState["gvCommissions"];
if (!Page.IsPostBack)
{
GridViewStructure();
AddNewRow();
}
else
{
dt = (DataTable)ViewState["gvCommissions"];
}
ViewState["gvCommissions"] = dt;
}
One thing I would add, it is not a good idea to save the table in view state.
I am having a problem with deleting gridview rows. I am populating my gridview by selecting value in a dropdownlist then by clicking the add button, value will be added in my gridview, here is my code:
In my aspx:
<asp:GridView ID="GridView1" runat="server"
CssClass="mGrid" EmptyDataText = "There are no records to display">
<Columns>
<asp:TemplateField ItemStyle-Width="10">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Id");
DataColumn dc1 = new DataColumn("Name");
//DataColumn dc2 = new DataColumn("Id");
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
// dt.Columns.Add(dc2);
ds.Tables.Add(dt);
Session["data"] = ds;
GridView1.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
foreach (GridViewRow row in GridView1.Rows)
{
SqlCommand cmdd = new SqlCommand("Insert into Profile (Id, profile_Id)VALUES(#id, #pid)", con);
cmdd.CommandType = System.Data.CommandType.Text;
cmdd.Parameters.AddWithValue("#id", row.Cells[1].Text);
cmdd.Parameters.AddWithValue("#pid", txtbid.Text);
cmdd.ExecuteNonQuery();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
DataSet ds = (DataSet)Session["data"];
DataRow dr = ds.Tables[0].NewRow();
dr[0] = DropDownList1.Text.Trim();
dr[1] = DropDownList1.SelectedItem;
//dr[2] = txtId.Text.Trim();
ds.Tables[0].Rows.Add(dr);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Now, I am trying to remove checked rows on my gridview with this code:
protected void btnRemove_Click(object sender, EventArgs e)
{
ArrayList del = new ArrayList();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkDelete = (CheckBox)row.Cells[0].FindControl("CheckBox1");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
string id = row.Cells[1].Text;
del.Add(id);
}
}
}
}
GridView1.DataBind();
}
With the btnRemove codes above, If I clicked it, it'll remove all values in my gridview even the unchecked rows, what I want is that just the checked rows not all. And are there any other simple way of removing rows in a gridview than using checkbox? I am using c# with asp.net.
Remove the rows but don't re-bind the gridview.
Use GridView.DeleteRow method to remove the rows you filtered in the arraylist del.
When you call GridView1.DataBind(); without setting a DataSource you will be binding nothing.
Similar
How to delete row from gridview?
I have grid view in which I want to update row but it is not happening. The datasource is a DataTable. Please help.
Below is the markup
<asp:GridView ID="GrdV" runat="server" AutoGenerateColumns="false"
OnRowEditing="GrdV_RowEditing" OnRowUpdating="GrdV_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Clip Description">
<ItemTemplate>
<asp:Label ID="lblDescrptn" runat="server" Text='<%# Bind("Description") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="descTbx" runat="server" Text='<%# Bind("Description") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
and this is code behind
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Retrieve the row being edited.
int index = GrdV.EditIndex;
GridViewRow row = GrdV.Rows[index];
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[index]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
On debugging , I find that textbox is passing empty string t1.Text ="" even after I have filled textbox with new values.
I think the error is in line
TextBox t1 = row.FindControl("descTbx") as TextBox;
PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GrdV.DataSource = Session["tmdataTable"];
GrdV.DataBind();
}
DataTable Finaldt = getTable();
GrdV.DataSource = Finaldt;
GrdV.DataBind();
Session["tmdataTable"] = Finaldt;
}
EditIndex isn't available, you need e.RowIndex from the GridViewUpdateEventArgs
// Retrieve the row being edited.
DataTable dt = (DataTable)Session["tmdataTable"];
GridViewRow row = GrdV.Rows[e.RowIndex];
TextBox t1 = row.FindControl("descTbx") as TextBox;
dt.Rows[row.DataItemIndex]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
Alter your code a bit and check. Change EditIndex to e.RowIndex
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GrdV.Rows[e.RowIndex]; // this line is changed
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[row.DataItemIndex]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
Have you done this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GrdV.DataSource = Session["tmdataTable"];
GrdV.DataBind();
}
}
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (e.Item is GridDataItem)
{
// Retrieve the row being edited.
int index = GrdV.EditIndex;
GridViewRow row = GrdV.Rows[index];
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[index]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
}
I have a data table which already has some values, plus it is getting values from a textbox below.
Now my problem is when i dont enter a value in the textbox it still enters in the data table.
I dont want it to do that..
The code can run on any machine... any suggestions????
Thanks
public partial class WebForm6 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
// Initialize a DataTable
if (!Page.IsPostBack)
{
dt = new DataTable();
// Initialize DataColumn
DataColumn myDataColumn = new DataColumn();
//// initialize a new instance of DataColumn to add another column with different properties.
//myDataColumn = new DataColumn();
myDataColumn.ColumnName = "firstName";
// set DataType property of the column as String
myDataColumn.DataType = System.Type.GetType("System.String");
// Add and Create a Second DataColumn
dt.Columns.Add(myDataColumn);
// create a new row using NewRow() function of DataTable.
// dataRow object will inherit the schema of myDataTable to create a new row
DataRow dataRow = dt.NewRow();
dataRow["firstName"] = "John";
// add new data row to the data table.
dt.Rows.Add(dataRow);
// similarly adds the second row to the DataTable
dataRow = dt.NewRow();
dataRow["firstName"] = "Will";
dt.Rows.Add(dataRow);
Session["data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["Data"] == null)
{
dt.Columns.Add("firstName");
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
else
{
dt = (DataTable)Session["Data"];
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
} private void ClearControls()
{
txtName.Text = String.Empty;
}
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
DataRow dr;
dr = dt.NewRow();
dr["firstName"] = txtName.Text.ToString();
dt.Rows.Add(dr);
Session["Data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
and on .aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("firstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
any help....??
Change your method to be this:
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
if (!String.IsNullOrEmpty(txtname.Text))
{
DataRow dr = dt.NewRow();
dr["firstName"] = txtName.Text;
dt.Rows.Add(dr);
Session["Data"] = dt;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}