Adding rows to gridView - c#

I want to add new rows after the inserted rows. I have a button that shows bootstrap modal with some DropDownLists and Textboxes. The button in modal on click should insert the data from modal to the table. The problem is that when i try to add new row it will replace current row. What im doing wrong? Here is sample of my code:
.cs:
protected void addTrip_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dostawca = DropDownDostawca.SelectedValue.ToString();
cel = txtCel.InnerText;
krajZagr = "";
kraj = DropDownKraj.SelectedValue.ToString();
miasto = txtMiasto.Text;
if(rbKraj.Checked == true)
{
krajZagr = "Krajowa";
}
if(rbZag.Checked == true)
{
krajZagr = "Zagraniczna";
}
if(cel=="" || miasto=="" || kraj=="" || dostawca=="" )
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup2();", true);
}
else
{
if(gridViewTrips.Columns.Count == 0)
{
DataRow dr = dt.NewRow();
DataColumn dc = new DataColumn("DO_KOGO");
DataColumn dc2 = new DataColumn("CEL");
DataColumn dc3 = new DataColumn("KRAJOWA_ZAGRANICZNA");
DataColumn dc4 = new DataColumn("KRAJ");
DataColumn dc5 = new DataColumn("MIASTO");
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
else
{
DataRow dr = dt.NewRow();
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
}
}
.aspx:
<asp:GridView runat="server" id="gridViewTrips">
<EmptyDataTemplate>
<asp:Table ID="TableTrips" runat="server" CssClass="table table-bordered">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Do kogo</asp:TableHeaderCell>
<asp:TableHeaderCell>Cel</asp:TableHeaderCell>
<asp:TableHeaderCell>Krajowa/Zagraniczna</asp:TableHeaderCell>
<asp:TableHeaderCell>Kraj</asp:TableHeaderCell>
<asp:TableHeaderCell>Miasto</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</EmptyDataTemplate>
</asp:GridView>
EDIT: Now I see when I debug my project the IF what i have: "if(gridViewTrips.Columns.Count == 0)" after inserted one row shows me that I dont have any columns. Any ideas what is going on?

What about create GridView column first...
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn(v=vs.110).aspx
and then AddChild method?
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridview(v=vs.110).aspx

Related

How to dynamically populate a gridview where the dataset column length is not static/known [duplicate]

I have to dynamically add multiple gridview in ASP.net. There are no of gridview are genereated on the basis of selection.
If I have not understood wrong from title that add multiple grid view dynamically means want to add grid view from code behind at run time.
As GridView is a class in ASP.NET C# and we can create object of it and set its properties just like other class object like follows:
GridView objGV = new GridView();
objGV .AutoGenerateColumns = false;
and can add columns of different type like BoundField and TemplateField from code Like follows:
BoundField field = new BoundField();
field.HeaderText = "Column Header";
field.DataField = Value;
objGV .Columns.Add(field);
and finally can add this grid view object on .aspx under any container control like panel.
PanelId.Controls.Add(objGV );
For adding multiple grid instance just iterate above code in loop like:
for(int i=0;i<yourConditionCount;i++)
{
GridView objGV = new GridView();
objGV.ID="GV"+i; // ID of each grid view must be unique
// your code logic to set properties and events for grid view
PanelId.Controls.Add(objGV );
}
Hope I understood your requirement correctly and my explanation will be helpful for you.
private void BindDynaicGrd()
{
//instance of a datatable
DataTable dt = new DataTable();
//instance of a datarow
DataRow drow;
//creating two datacolums dc1 and dc2
DataColumn dc1 = new DataColumn("Code", typeof(string));
DataColumn dc2 = new DataColumn("Name", typeof(string));
//adding datacolumn to datatable
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
if (grd.Rows.Count > 0)
{
foreach (GridViewRow gvr in grdSites.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Checked == true)
{
Label lbl_Code = (Label)gvr.FindControl("lblCode");
Label lbl_Name = (Label)gvr.FindControl("lblName");
//instance of a datarow
drow = dt.NewRow();
//add rows to datatable
//add Column values
drow = dt.NewRow();
drow["Code"] = lbl_Code.Text;
drow["Name"] = lbl_Name.Text.ToString();
dt.Rows.Add(drow);
}
}
}
//set gridView Datasource as dataTable dt.
gridcl.DataSource = dt;
//Bind Datasource to gridview
gridcl.DataBind();
}
<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
DataSet ds = new DataSet();
ds = obj.GetMedicalGridWithAge(MphID, ProductCode);
if(ds.Tables.Count > 0)
{
if (ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView gv = new GridView();
gv.ID = "gv" + (i + 1);
gv.DataSource = ds.Tables[i];
gv.DataBind();
Panel1.Controls.Add(gv);
Label newLine = new Label(); newLine.Text = "<br/>";
Panel1.Controls.Add(newLine);
}
}
else
{
GridView gv = new GridView();
gv.ID = "gv" ;
gv.DataSource = null;
gv.DataBind();
Panel1.Controls.Add(gv);
}
}

how to assign values to DataKeyNames in gridview programatically using C#

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" };

How to display row number in gridview

I use code below but it didint work.. It didnt show me column with that field.
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
I add my other columns in code behind and meaby it's the problem?
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
Does anone have any idea how to do this in other way?
I try to this like below but it's counts my row number after all data I Fill() into a DataTable and then add to each row a number
DataColumn columnIndexRow = new DataColumn();
columnIndexRow.DataType = System.Type.GetType("System.Int32");
columnIndexRow.ColumnName = "id";
dt.Columns.Add(columnIndexRow);
for (int i = 0; i < dt.Rows.Count; i++)
{
// your index is in i
var row = dt.NewRow();
row["id"] = i;
dt.Rows.Add(row);
}
ADD row number field to DataTable
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
dt = AutoNumberedTable(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
private DataTable AutoNumberedTable(DataTable SourceTable)
{
DataTable ResultTable = new DataTable();
DataColumn AutoNumberColumn = new DataColumn();
AutoNumberColumn.ColumnName="S.No.";
AutoNumberColumn.DataType = typeof(int);
AutoNumberColumn.AutoIncrement = true;
AutoNumberColumn.AutoIncrementSeed = 1;
AutoNumberColumn.AutoIncrementStep = 1;
ResultTable.Columns.Add(AutoNumberColumn);
ResultTable.Merge(SourceTable);
return ResultTable;
}
Hope this might help. :)
Note: I haven't tested this code.
Thanks guys! I just find out the answer. I do something like updating a cell at row index and first column
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i][0] = i;
}

How to dynamically add gridview

I have to dynamically add multiple gridview in ASP.net. There are no of gridview are genereated on the basis of selection.
If I have not understood wrong from title that add multiple grid view dynamically means want to add grid view from code behind at run time.
As GridView is a class in ASP.NET C# and we can create object of it and set its properties just like other class object like follows:
GridView objGV = new GridView();
objGV .AutoGenerateColumns = false;
and can add columns of different type like BoundField and TemplateField from code Like follows:
BoundField field = new BoundField();
field.HeaderText = "Column Header";
field.DataField = Value;
objGV .Columns.Add(field);
and finally can add this grid view object on .aspx under any container control like panel.
PanelId.Controls.Add(objGV );
For adding multiple grid instance just iterate above code in loop like:
for(int i=0;i<yourConditionCount;i++)
{
GridView objGV = new GridView();
objGV.ID="GV"+i; // ID of each grid view must be unique
// your code logic to set properties and events for grid view
PanelId.Controls.Add(objGV );
}
Hope I understood your requirement correctly and my explanation will be helpful for you.
private void BindDynaicGrd()
{
//instance of a datatable
DataTable dt = new DataTable();
//instance of a datarow
DataRow drow;
//creating two datacolums dc1 and dc2
DataColumn dc1 = new DataColumn("Code", typeof(string));
DataColumn dc2 = new DataColumn("Name", typeof(string));
//adding datacolumn to datatable
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
if (grd.Rows.Count > 0)
{
foreach (GridViewRow gvr in grdSites.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Checked == true)
{
Label lbl_Code = (Label)gvr.FindControl("lblCode");
Label lbl_Name = (Label)gvr.FindControl("lblName");
//instance of a datarow
drow = dt.NewRow();
//add rows to datatable
//add Column values
drow = dt.NewRow();
drow["Code"] = lbl_Code.Text;
drow["Name"] = lbl_Name.Text.ToString();
dt.Rows.Add(drow);
}
}
}
//set gridView Datasource as dataTable dt.
gridcl.DataSource = dt;
//Bind Datasource to gridview
gridcl.DataBind();
}
<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
DataSet ds = new DataSet();
ds = obj.GetMedicalGridWithAge(MphID, ProductCode);
if(ds.Tables.Count > 0)
{
if (ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
GridView gv = new GridView();
gv.ID = "gv" + (i + 1);
gv.DataSource = ds.Tables[i];
gv.DataBind();
Panel1.Controls.Add(gv);
Label newLine = new Label(); newLine.Text = "<br/>";
Panel1.Controls.Add(newLine);
}
}
else
{
GridView gv = new GridView();
gv.ID = "gv" ;
gv.DataSource = null;
gv.DataBind();
Panel1.Controls.Add(gv);
}
}

how to delete from gridview without database "check to determine if the object is null before calling the method"

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();
}
}

Categories