im using asp.net and c#
i need to fill gridview from textbox values,
my code is,
<div>
<table class="style1">
<tr>
<td>
Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Address
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Number
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</div>
then my .aspx code is,
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
//First fill all the date present in the grid
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0];
dr["Address"] = GridView1.Rows[intCnt].Cells[1];
dr["Number"] = GridView1.Rows[intCnt].Cells[2];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dr["Address"] = TextBox2.Text;
dr["Number"] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
but the result is, adding single row with value...
next row value is not adding properly...
problem is,
the second entry of textbox values are stored like "System.Web.UI.WebControls.DataControlFieldCell " is display in each cell of second row...
it should be like
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
that is reason you are not getting value properly.
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0].Text;
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
dr["Number"] = GridView1.Rows[intCnt].Cells[2].Text;
dt.Rows.Add(dr);
}
}
Extract grid view rows using for each loop , and use the Text property of each cell to assign to your DataTable again.
Here's your click command:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
foreach (GridViewRow gr in GridView1.Rows)
{
//using gridviewrow
if (gr.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = gr.Cells[0].Text;
dr["Address"] = gr.Cells[1].Text;
dr["Number"] = gr.Cells[2].Text;
dt.Rows.Add(dr);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
You are assigning object of cells not the values.
Get the Text property of cells.
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");
//First fill all the date present in the grid
for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt++)
{
if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = GridView1.Rows[intCnt].Cells[0].Text;
dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
dr["Number"] = GridView1.Rows[intCnt].Cells[2].Text;
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dr["Address"] = TextBox2.Text;
dr["Number"] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Related
I have a GridView. I am adding columns in it through c# in GridView gvExemptSub and retrieving data from another GridView gvSubj on button click. I want to assign data row values to DataKeyNames which I am retrieving from another GridView but I don't know how.
<asp:GridView ID="gvExemptSub" runat="server" Width="100%" DataKeyNames="LID,BID">
<Columns>
</Columns>
</asp:GridView>
protected void BtnAddSubj_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "ExemptSubj";
dt.Columns.Add("QUALIFICATION", typeof(string));
dt.Columns.Add("SUBJECT", typeof(string));
dt.Columns.Add("LEVEL", typeof(string));
dt.Columns.Add("UNIVERSITY", typeof(string));
DataRow dr;
foreach (GridViewRow srow in gvSubj.Rows)
{
if (srow.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr[0] = ddlQualification.SelectedItem;
string SUBJECT = srow.Cells[1].Text;
SUBJECT = SUBJECT.Replace("amp;", "");
dr[1] = SUBJECT;
dr[4] = int.Parse(gvSubj.DataKeys[srow.RowIndex]["LEVEL_ID"].ToString());
dr[2] = srow.Cells[2].Text;
dr[3] = ddlUNI.SelectedItem.Text;
dr[5] = ddlUNI.SelectedValue;
dt.Rows.Add(dr);
}
}
ViewState["ExemptSubj"] = dt;
//gvExemptSubj.DataKeyNames = (dr[4], dr[5])
gvExemptSubj.DataSource = dt;
gvExemptSubj.DataBind();
}
You can bind them programmatically with an string array:
GridView1.DataKeyNames = new string[2] { "ColumnA", "ColumnB" };
I have 2 dropdownlists in grid view. The selection of the first one (EqpCatDDL) will determine what values the second one (DescripDDL) will be populated with.
However, everytime I click the Add New Row button, the DescripDDL dropdownlist clears up. I don't know why it does that. The following is the code:
aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="Gridview1" runat="server" ShowFooter="True" AutoGenerateColumns="False"
OnRowDataBound="Gridview1_RowDataBound">
<Columns>
<asp:BoundField DataField="S/N" HeaderText="S/N" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="EqpCatDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="EqpCatDDL_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="DescripDDL" runat="server" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<contenttemplate>
<asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />
</contenttemplate>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow(); //create a datatable to bind to GridView
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("S/N", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dr = dt.NewRow();
dr["S/N"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
Button btn = row.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btn);
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
//extract the TextBox values
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//Locate controls in GridView
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
//Save control values into DataTable
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["S/N"] = i + 1;
drCurrentRow["Column1"] = ddl1.SelectedValue.ToString();
drCurrentRow["Column2"] = ddl2.SelectedValue.ToString();
drCurrentRow["Column3"] = box3.Text;
drCurrentRow["Column4"] = box4.Text;
dtCurrentTable.Rows[rowIndex]["Column1"] = ddl1.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column2"] = ddl2.SelectedValue.ToString();
dtCurrentTable.Rows[rowIndex]["Column3"] = box3.Text;
dtCurrentTable.Rows[rowIndex]["Column4"] = box4.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData(); //Set Previous Data from DataTable to GridView on Postbacks from Add New Row button click
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < (dt.Rows.Count-1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.Text = dt.Rows[i]["Column1"].ToString();
ddl2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
//Populate Item Name dropdownlist from EqpCat column in EqpCategory table
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
//Find the DropDownList in the Row
DropDownList EqpCatDDL = (e.Row.FindControl("EqpCatDDL") as DropDownList);
SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT EqpCat FROM EqpCategory", connection);
cmd1.Connection.Open();
SqlDataReader ddlValues1;
ddlValues1 = cmd1.ExecuteReader();
EqpCatDDL.DataSource = ddlValues1;
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataValueField = "EqpCat";
EqpCatDDL.DataBind();
cmd1.Connection.Close();
cmd1.Connection.Dispose();
//Add Default Item in the DropDownList
EqpCatDDL.Items.Insert(0, new ListItem("--Select--"));
}
}
//Populate Description dropdownlist based on selected value of Item Name dropdownlist
protected void EqpCatDDL_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
GridViewRow gvr = (GridViewRow)((DropDownList)sender).Parent.Parent;
DropDownList EqpCatDDL = gvr.FindControl("EqpCatDDL") as DropDownList;
DropDownList DescripDDL = gvr.FindControl("DescripDDL") as DropDownList;
string cate = EqpCatDDL.SelectedValue.ToString();
SqlCommand cmd2 = new SqlCommand("SELECT Description FROM EqpCategory WHERE EqpCat = '" + cate + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
DescripDDL.DataSource = ddlValues2;
DescripDDL.DataTextField = "Description";
DescripDDL.DataValueField = "Description";
DescripDDL.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
//Add Default Item in the DropDownList
DescripDDL.Items.Insert(0, new ListItem("--Select--"));
}
I am currently using: Visual Studio 2010 with SSMS 2008
Just modify your SetPreviousData Function
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < (dt.Rows.Count - 1); i++)
{
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd2 = new SqlCommand(""SELECT Description FROM EqpCategory WHERE EqpCat = '" + Convert.ToInt32(ddl1.SelectedValue) + "'", connection);
cmd2.Connection.Open();
SqlDataReader ddlValues2;
ddlValues2 = cmd2.ExecuteReader();
ddl2.DataTextField = "Description";
ddl2.DataValueField = "Description";
ddl2.DataSource = ddlValues2;
ddl2.DataBind();
cmd2.Connection.Close();
cmd2.Connection.Dispose();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
}
}
Use SelectedValue (https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx) instead of text to set the selected item.
E.g.:
ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
I have a gridview and output generated is
But I want to remove the Column_Name column and want this type of output
Never change SQL query because in this way the query works according to my logic. And I also want to remove   in every textbox and how can I get all the gridview data by using loop and save in SQL Server database?
ASPX:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<form id="form" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="load" Text="gridview" />
<asp:Button ID="Button2" runat="server" OnClick="show" Text="Button" />
<asp:Button ID="Button3" runat="server" OnClick="save" Text="Save" />
</form>
</asp:Content>
Codebehind:
SqlConnection cnn = new SqlConnection("Data Source=LIFE_WELL;Initial Catalog=db_compiler;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
string query = "USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='deptt'";
SqlCommand cmd = new SqlCommand(query, cnn);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adp.Fill(dt);
Session["num"] = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataColumn dc = new DataColumn(dt.Rows[i]["Column_Name"].ToString());
dt.Columns.Add(dc);
}
DataRow r = table.NewRow();
GridView1.DataSource = table;
GridView1.DataBind();
cnn.Close();
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
Session["table"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
txt.Text = e.Row.Cells[i].Text;
e.Row.Cells[i].Text = "";
e.Row.Cells[i].Controls.Add(txt);
}
}
}
Change Your Codebehind code:
protected void Page_Load(object sender, EventArgs e)
{
If(!IsPostBack)
{
string query = "USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='deptt'";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adp.Fill(dt);
Session["num"] = dt.Rows.Count;
for (int i = 0; i < dt.Rows.Count; i++)
{
DataColumn dc = new DataColumn(dt.Rows[i]["Name"].ToString());
table.Columns.Add(dc); // Make this Column in 2nd DataTable and bind that to Gridview
}
DataRow r = table.NewRow();
Session["table"] = dt;
table.Rows.Add(r); // Add as many row you want to add with for loop
Gridview1.DataSource = table;
Gridview1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
e.Row.Cells[i].Controls.Add(txt);
}
}
}
You can try with this modified RowDataBound event handler:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i < e.Row.Cells.Count; i++) // Does not process the first cell
{
TextBox txt = new TextBox();
TableCell cell = e.Row.Cells[i];
txt.Text = cell.Text.Replace(" ", ""); // Removes
cell.Text = "";
cell.Controls.Add(txt);
}
}
e.Row.Cells.RemoveAt(0); // Removes the first cell in the row
}
This is my program that page load the gridview and retrieve the database record to textbox and i put a add new button wish to add new row exactly like that row but the textbox is empty.
I wanted to create a new row in GridView while click add new button while my TextBox is retrieve data from database. I try to run the code but it is nothing happen when i click the button. Hope someone may help. Thanks.
My front end code
<Columns>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Font-Bold="true" Font-Size="Medium">Name</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" CssClass="NormalInputTextField" Text='<%#Eval("SLMN") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnDelete" runat="server" Text="Delete" CssClass="btn btn-primary" CommandName="remove" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-BorderStyle="None" HeaderStyle-CssClass="display_none">
<ItemTemplate>
<asp:Button ID="BtnSearch2" runat="server" Text="Search" CssClass="btn btn-primary" CommandName="ViewComments" OnClientClick="javascript:saveData(this,'grid')"/>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" BorderStyle="None"/>
<FooterTemplate>
<asp:Button ID="BtnAdd" runat="server" Text="Add New Row" CssClass="btn btn-primary" OnClick="ButtonAdd_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
My back end code
private void AddNewRowToGrid()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dr = dt.NewRow();
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
}
My onclick event to call add new function
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
My gridview tag
<grd:MultiSelectGridView ID="grid2" runat="server" Width="500px"
CssClass="paging_gridview" AllowPaging="True"
AutoGenerateColumns ="false" PageSize="10" PagerType="Custom"
ShowFooter="true" OnRowDeleting="grid2_RowDeleting"
MultiSelectDataKeyName="Urid,Name" ShowHeaderWhenEmpty="true"
MultiSelectColumnIndex="0" EnableMultiSelect="false" GridLines="None" BorderStyle="None" OnRowCommand="grid2_RowCommand"
>
i bind my record to gridview by page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Loadgrid();
}
}
private void Loadgrid()
{
string branch = txtBranch.Text.Trim();
string name = txtName.Text.Trim();
string sql = "SELECT * FROM fcs_cotmdl WHERE TMDL= '" + name + "'AND CONO='" + branch + "' ";
SqlDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr_epsi"].ConnectionString;
SqlDataSource2.ConnectionString = SqlDataSource2.ConnectionString.Replace("Provider=OraOLEDB.Oracle.1;", "");
SqlDataSource con = new SqlDataSource();
SqlDataSource2.SelectCommand = sql;
grid2.DataSourceID = "SqlDataSource2";
grid2.DataBind();
}
Following tutorial details the exact same scenario. Please refer to it.
Adding Dynamic Rows to Gridview on Button Click
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
//Instead of all the textboxes, use the button as you require.
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
And then the SetPreviousData() Function:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
Then inside your Click Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
From your Load grid method you should retrieve the data as a data table and bind to grid. And save in in session. Like this:
private void Loadgrid()
{
var dt = new DataTable();
using (var conn = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
var command = new SqlCommand();
command.Connection = conn;
command.CommandText = "SELECT * FROM [dbo].[T1]";
command.CommandType = CommandType.Text;
using (var adaptor = new SqlDataAdapter(command))
{
if (conn.State == ConnectionState.Closed) conn.Open();
adaptor.Fill(dt);
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Session["ss"] = dt;
grid2.DataSource = dt;
grid2.DataBind();
}
private void AddNewRowToGrid()
{
DataTable dt = (DataTable) Session["ss"];
DataRow dr = null;
DataRow newBlankRow1 = dt.NewRow();
dt.Rows.Add(newBlankRow1);
grid2.DataSource = dt;
grid2.DataBind();
Session["ss"] = dt;
}
After add an empty row also you need to bind data to grid again.
The ff are codes in my .cs file
private void BindGridview(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Code", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Course", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Credit", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
// If ViewState has a data then use the value as the DataSource
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
// Bind GridView with the initial data assocaited in the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();
}
// Store the DataTable in ViewState to retain the values
ViewState["CurrentData"] = dt;
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[e.RowIndex].Delete();
ViewState["dt"] = dt;
BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Code = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[3].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + Code + "?')){ return false; };";
}
}
}
}
protected void cboCourseCode_SelectedIndexChanged(object sender, EventArgs e)
{
this.Populate_Course_Details();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
/* DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Code"), new DataColumn("Course"), new DataColumn("Credit") });
dt.Rows.Add(this.cboCourseCode.Text, this.txtCourseName.Text, this.txtCredit.Text);
ViewState["dt"] = dt;
BindGrid();*/
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGridview(count);
}
else
{
BindGridview(1);
}
}
My aspx file also has this gridview
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Course" HeaderText="Course" />
<asp:BoundField DataField="Credit" HeaderText="Credit" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
When I start to delete, I get this error:
check to determine if the object is null before calling the method
Error Reason
in OnRowDeleting function you are creating datatable and assigning viewstate["dt"],which doesn't have current data. that's why it shows Object is Null
Solution
Try This
First make one of the column as data key.consider i want to make "Code" column as datakey.
datakey will help to find specific row to delete
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound" DataKeyNames="Code">
After That in .cs code
create a datatable with currentdata
make "Code" column as primary key
find particular code(which you want to delete)using find()
then delete that row using delete() function
Reflect the deletion in viewsate["currentdata"]
then bind to gridview
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string code = GridView1.DataKeys[e.RowIndex].Value.ToString();
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
dt.Rows.Find(code).Delete();
ViewState["CurrentData"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}