How to edit the GridView - c#

I want to edit the GridView without involving the database
protected void myGridView_RowUpdating(object sender,GridViewUpdateEventArgs e)
{
string reg = (myGridView.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)myGridView.Rows[e.RowIndex];
TextBox name = (TextBox)row.Cells[1].Controls[0];
TextBox email = (TextBox)row.Cells[2].Controls[0];
myGridView.EditIndex = -1;
BindGird();
}
this my bindgrid fucntion:
protected void BindGird()
{
DataTable dt = (DataTable)Session["myCart"];
this.myGridView.DataSource = dt; this.myGridView.DataBind();
}
and this is the row editing event
protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex; BindGird();
}

Related

Gridview row in editing mode when I press "Insert" button? asp.net C#

I have a gridview and some control below the griview. I insert values from "control" and press "Insert" button then the values are inserted into the gridview row. Here is the gridview image when I insert values in control
and press the "Insert" button
and when I click on the "edit" button in griview the values of the selected edit row are displayed below the "controls" but when I update values in the control and click again "insert" then the row automatically edits the data, but I don't want this, I want that when I click on "insert" again that the row should not display in edit mode, here is the image
I want that when I click on "insert" button that the row values are replaced with new values.
Here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("Column Name", System.Type.GetType("System.String"));
dt.Columns.Add("Data Type", System.Type.GetType("System.String"));
dt.Columns.Add("Allow Null", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Primary Key", System.Type.GetType("System.Boolean"));
Session["MyDataTable"] = dt;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["ID"] = t.Rows.Count + 1;
row1["Column Name"] = TextBox1.Text;
row1["Data Type"] = DropDownList1.Text;
row1["Allow Null"] = Null.Checked == true ? "true" : "false";
row1["Primary Key"] = Primary.Checked == true ? "true" : "false";
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView2.DataSource = t;
GridView2.DataBind();
TextBox1.Text = String.Empty;
DropDownList1.Text = "Select DataType";
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
t.Rows.RemoveAt(e.RowIndex);
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
//GridView2.EditIndex = e.NewEditIndex;
// TextBox1.Enabled = true;
//GridViewRow row = GridView2.Rows[e.NewEditIndex];
TextBox1.Text = GridView2.Rows[e.NewEditIndex].Cells[2].Text.ToString();
DropDownList1.Text = GridView2.Rows[e.NewEditIndex].Cells[3].Text.ToString();
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}
public void cancel(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}

Dynamically added gridview's linkbutton not working

I have a gridview that has dynamically created columns.
Right now all the data is showing in its respective place but I am unable to get my link button to work. (Gridview disappears)
Here is my backend code, the gridview used is just an empty gridview
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
}
GridView1.DataBind();
}
string selectedID = null;
private void BindGrid(List<string> SelectedInfo)
{
DataTable dt = new DataTable();
//Dynamically adding columns and setting first column added as ID
selectedID = SelectedInfo[0];
for (int i = 0; i < SelectedInfo.Count; i++)
{
dt.Columns.Add(new DataColumn(SelectedInfo[i], typeof(string)));
}
List<string[]> InfoList = getInfoList(SelectedInfo);
for (int i = 0; i < InfoList.Count; i++)
{
dt.Rows.Add(InfoList[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //Adding link button to first column
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[selectedID].ToString();
e.Row.Cells[0].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
//Popup the selected row ID
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Row ID" + id + "')", true);
}
protected void CheckBoxList2_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> SelectedInfo = new List<string>();
for (int i = 0; i < CheckBoxList2.Items.Count; i++)
{
if (CheckBoxList2.Items[i].Selected)
{
SelectedInfo.Add(CheckBoxList2.Items[i].Text);
}
}
BindGrid(SelectedInfo);
}
If you need to create controls at runtime, you better use the RowCreated event:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //Adding link button to first column
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[selectedID].ToString();
e.Row.Cells[0].Controls.Add(lnkView);
}
}
Otherwise you have to bind your GridView on every postback inViewDetails the Page_Load event.
Anyway if your GridView disappears, it's just because you have to bind it again in the ViewDetails method.
I hope below code will help you.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
}
this.BindGrid();
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[2].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + "')", true);
}

Dynamically adding multiple rows in data table in C#

I have been tried to use the DATATABLE for storing the values for the entire application. I haven't use any database for storing values permanently. This are the dummy values I could use through out the application.
The issue is actually whenever I add a new row value into my DATATABLE it just overrides the previous values in the DATATABLE instead of adding an new row.
Is there any chance to add multiple rows to the DATATABLE dynamically and I can use it through out the application session.
** MY REGISTER PAGE**
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable;
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
if (!IsPostBack)
{
if (Session["name"] != null)
{
myDataTable = Session["name"] as DataTable;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
myDataTable.Rows.Add(new object []{ TextBox1.Text ,TextBox2.Text,TextBox3.Text , TextBox4.Text,TextBox5.Text ,TextBox6.Text });
HttpContext.Current.Session["name"] = myDataTable;
if (Session["name"] != null)
{
Response.Write("success");
}
}
MY LOGIN PAGE
public partial class login : System.Web.UI.Page
{
DataTable dtResult;
protected void Page_Load(object sender, EventArgs e)
{
dtResult = (DataTable)Session["name"];
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dtResult.Rows.Count; i++)
{
string un = dtResult.Rows[i].Field<string>("username");
string fn = dtResult.Rows[i].Field<string>("password");
if (TextBox1.Text == un && TextBox2.Text == fn)
{
//Response.Write("success");
Response.Redirect("home.aspx");
}
}
}
Issue:
At every Postback you are creating a new datatable and overriding it to the previous:
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
//....
HttpContext.Current.Session["name"] = myDataTable; //overriding to the previous
So when you click on the button to add the new row, it posts back, and recreates a new datatable and then add a new row to that table.
Solution:
You just need to modify the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null) //this is you have to do at every postback
{
myDataTable = Session["name"] as DataTable;
}
if (!IsPostBack)
{
//if it is not post back, create a new DataTable and add values to it
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
}
}

Adding new row to a DataTable

I have a GeidView in my form and I have a button which add new records to the GridView by adding a row to a Datatable and then make this DataTable as the GridContol's Data Source.
The problem is when I add a new record it display in the GridView but when I add another rocord it doesn't display in the GridView, The GridView always contains the first row I added to the DataTable !
So please could you help me to solve this problem ?
This is the source code :
private DataTable recompensesTable;
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
private DataTable MakeRecomponsesTable()
{
DataTable recmpensesTable = new DataTable("Recompenses");
var anneeColumn = new DataColumn();
anneeColumn.DataType = Type.GetType("System.Int32");
anneeColumn.ColumnName = "Année";
recmpensesTable.Columns.Add(anneeColumn);
var prixLiteraireColumn = new DataColumn();
prixLiteraireColumn.DataType = Type.GetType("System.String");
prixLiteraireColumn.ColumnName = "Prix Litéraire";
recmpensesTable.Columns.Add(prixLiteraireColumn);
return recmpensesTable;
}
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
recompenseGridControl.DataSource = recompensesTable;
}
In your Page_Load you have recompensesTable = MakeRecomponsesTable();. That overwrites the changes and recreate the datatable values
On page postback, variables are restored to their default values and they need to be recreated. You can use Session to maintain your values
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataTable recompensesTable = MakeRecomponsesTable();
Session["recompensesTable"] = recompensesTable; //Save it to session the first time
recompenseGridControl.DataSource = recompensesTable;
}
}
and retrieve the session preserved value
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataTable recompensesTable = (DataTable) Session["recompensesTable"]; //retrieve it from session
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
Session["recompensesTable"] = recompensesTable; //save it back to session
recompenseGridControl.DataSource = recompensesTable;
}
change your
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
To
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!IsPostback)
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
You also must save the datatable to session
the recmpensesTable is always a new DateTable, you should save it to session for next use.

ASP .NET RowUpdating GridView Troubles

I'm having trouble with the RowUpdating Method. My GridView is connected to our local SQL Server, and I'm trying to update the data. Here is the code for the RowUpdating Method from MSDN.
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
I get this error:
System.NullReferenceException: Object reference not set to an instance of an object.
try this code once.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox tname = (TextBox)row.FindControl("nam");
TextBox tques = (TextBox)row.FindControl("que");
MySqlCommand cmd = new MySqlCommand("update exam set name1=#name,ques=#ques where id = #id", con);
cmd.Parameters.Add("#id", MySqlDbType.Int16).Value = id;
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = tname.Text.Trim();
cmd.Parameters.Add("#ques", MySqlDbType.VarChar,40).Value = tques.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bind();
}
Not all GridViewRow have a DataItem.
You should add a if block around your code and verify the row being updated is of type DataRow.
if (e.Row.RowType == DataControlRowType.DataRow)
{
your code here...
}
More regarding RowTypes : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowtype.aspx
public void bindGvEdit()
{
GridView1.DataSource = obj1.SelectAlltbl();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindGvEdit();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindGvEdit();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
obj1.Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
obj1.Name = ((TextBox)row.Cells[1].Controls[1]).Text;
obj1.Description = ((TextBox)row.Cells[2].Controls[1]).Text;
obj1.Updatetbl();
GridView1.EditIndex = -1;
bindGvEdit();
}

Categories