ASP.NET GridView Column Remove - c#

I have a GridView with some predefined Columns and some generated in code. The idea is that I show Columns according to category, selected by user. I cannot create all Columns and just hide them because I don't know how many Columns I will need. I manage to generate Columns I needed, but the problem starts when I try to remove generated Columns. Situation looks like this:
On first load I see GridView of all categories.
After clicking in ListBox I get result I want. 1 additional Column is created (RemoveAt is not called, because no additional Columns were yet created.).
After clicking in other ListBox Item I still get result I want. Column created last time where deleted and new Column added.
At this point, if I click any other ListBox Item in LicensesCategoriesListBox_SelectedIndexChanged on debugging I see that all of GridView TemplateFields are empty (http://tinypic.com/r/98vdkm/8).
If I comment section gridView.Columns.RemoveAt(i - 1) everything works fine, just Columns keeps generating and generating. Any ideas why all of my TemplateFields, written in my Page becomes empty?
My Page looks like this:
<asp:ListBox ID="licensesCategoriesListBox" runat="server" AutoPostBack="true" OnSelectedIndexChanged="LicensesCategoriesListBox_SelectedIndexChanged" />
<asp:GridView ID="licencesGridView" runat="server" AutoGenerateColumns="False" Caption="Licencijos" DataKeyNames="id" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="Pavadinimas">
<EditItemTemplate>
<asp:TextBox ID="licenceNameTextBox" runat="server" MaxLength="50" Text='<%# Bind("name") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="newLicenceNameTextBox" runat="server" MaxLength="50" ToolTip="Pavadinimas" />
</FooterTemplate>
<ItemTemplate>
<span><%# Eval("name") %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Kategorija">
<EditItemTemplate>
<asp:DropDownList ID="licenceCategoryDropDownList" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="newLicenceCategoryDropDownList" runat="server" ToolTip="Kategorija">
<asp:ListItem Text="Pasirinkite kategoriją:" />
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<span><%# Eval("category") %></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
FillLicences(ref licencesGridView);
}
}
protected void LicensesCategoriesListBox_SelectedIndexChanged(object sender, EventArgs e) {
FillLicences(ref licencesGridView, licensesCategoriesListBox.SelectedValue); /// Value is ID of category.
}
public void FillLicences(ref GridView gridView, string category = "") {
DataTable dataTable;
ushort categoryId;
if (UInt16.TryParse(category, out categoryId)) {
PutAdditionalColumns(ref gridView, categoryId);
dataTable = sqlCommands.GetLicences(categoryId); /// Returns DataTable [name], [category] and additional fields that I add in PutAdditionalColumns method.
} else {
dataTable = sqlCommands.GetAllLicences(); /// Returns DataTable with only [name], [category]
}
gridView.DataSource = dataTable;
gridView.DataBind();
}
public void PutAdditionalColumns(ref GridView gridView, uint category) {
for (ushort i = (ushort)gridView.Columns.Count; i > 2; i--) { /// Removes columns at the end (created for other category)
gridView.Columns.RemoveAt(i - 1);
}
foreach (var pair in sqlCommands.GetLicencesCategoryAttributes(category)) { /// Takes additional field needed.
TemplateField field = new TemplateField(); /// New empty column.
field.AccessibleHeaderText = pair.Key.ToString();
field.HeaderText = pair.Value;
gridView.Columns.Add(field);
}
}

Any ideas why all of my TemplateFields, written in my Page becomes
empty?
Because each of those fields is considered a Column. You're removing them in the code.
If this is your issue, you need some way to seperate columns defined in the aspx to the ones created in the code.
I'd use DataColumn.ExtendedProperties to do this.
Whenever you add a column from code, add a value to ExtendedProperties, showing that it was created in the code.
//...
TemplateField field = new TemplateField(); /// New empty column.
field.AccessibleHeaderText = pair.Key.ToString();
field.HeaderText = pair.Value;
DataColumn ourNewColumn = gridView.Columns.Add(field);
ourNewColumn.ExtendedProperties.Add("CreatedInCode", true);
//...
And then when you come to delete them, only delete them if they have this property set.
//...
if( gridView.Columns[i - 1].ExtendedProperties.ContainsKey("CreatedInCode") ) {
gridView.Columns.RemoveAt(i - 1);
}
//...

Related

Copy Paste a row in a asp:GridView using C# in a web application

So I have a web application that uses a GridView.
We currently add 1 new blank record at a time fill it in and move on. There are times when the data needing to be entered has several fields that need to be duplicated. Is there a way to add a blank row, fill it in , and then copy that row and paste it back into the GridView?
I've looked at clone, but i haven't seen anything that works in a web application. Thanks for any advice.
Well, one way, is you could add a copy button to the grid?
Say we have this grid:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
cssclass="table table-hover borderhide">
<Columns>
<asp:TemplateField HeaderText ="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFirst" runat="server" Text = '<%# Eval("FirstName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLast" runat="server" Text = '<%# Eval("LastName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="City">
<ItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Active">
<ItemTemplate>
<asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Copy">
<ItemTemplate>
<asp:ImageButton ID="cmdCopy" runat="server" Text="Copy"
ImageUrl="~/Content/copy1600.png" Height="32px" Width="32px"
OnClick="cmdCopy_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save" CssClass="btn-primary" OnClick="cmdSave_Click1" />
<asp:Button ID="cmdAdd" runat="server" Text="Add Row" CssClass="btn-primary" style="margin-left:20px" OnClick="cmdAdd_Click1"/>
<br />
So, code to load this grid up
private DataTable rstPeople = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
ViewState["MyTable"] = rstPeople;
}
else
rstPeople = (DataTable)ViewState["MyTable"];
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from People",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstPeople.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
}
And the add row button code:
protected void cmdAdd_Click1(object sender, EventArgs e)
{
GridToTable(); // user may have edits
// add a new row to the grid
DataRow OneRow = rstPeople.NewRow();
OneRow["Age"] = 0;
OneRow["Active"] = true;
rstPeople.Rows.Add(OneRow);
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
So we click on add row, and that gives us this:
So, we have that blank row. But, in place of add row, we could click the copy button, and that would add a row - but copy from current. (I suppose we could have a copy + paste button - but that's WAY TOO much UI here).
So, add row = add blank row.
but, copy row button - add row - copy.
The code for that looks like this:
protected void cmdCopy_Click(object sender, ImageClickEventArgs e)
{
GridToTable(); // user might have done some editing
ImageButton cmdCopy = (ImageButton)sender;
GridViewRow gvRow = (GridViewRow)cmdCopy.Parent.Parent;
DataRow CopyFrom = rstPeople.Rows[gvRow.RowIndex];
DataRow OneRow = rstPeople.NewRow();
OneRow["Age"] = 0;
OneRow["FirstName"] = CopyFrom["FirstName"];
OneRow["LastName"] = CopyFrom["LastName"];
OneRow["City"] = CopyFrom["City"];
OneRow["Active"] = CopyFrom["Active"];
rstPeople.Rows.Add(OneRow);
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
Now I not shared how teh save button works.
So, the user now can add new rows. Tab around - edit any row. or even copy a new row (and again, edit some more).
So save the whole mess and grid back to the database, we
Send Grid back to table
Send table back to database.
So the save all button is thus this:
protected void cmdSave_Click1(object sender, EventArgs e)
{
GridToTable();
// now send table back to database with updates
string strSQL = "SELECT ID, FirstName, LastName, City, Active from People WHERE ID = 0";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daupdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(daupdate);
daupdate.Update(rstPeople);
}
}
again, really simple. And note how we did not bother with templates etc. (too messy, and really not less code then above).
I suppose you could have for a new row a "paste" icon, but if the users going to have to pick a row and copy - might as well make it "add row + copy" in one operation.
(and it not really a copy button, but more of a "duplicate row" button.
Only routine not posted was the GridToTable. This works, since we always persist the table, but any edits in GV have to be send back to the table, and thus we use this:
void GridToTable()
{
// pull grid rows back to table.
foreach (GridViewRow rRow in GridView1.Rows)
{
int RecordPtr = rRow.RowIndex;
DataRow OneDataRow;
OneDataRow = rstPeople.Rows[RecordPtr];
OneDataRow["FirstName"] = ((TextBox)rRow.FindControl("txtFirst")).Text;
OneDataRow["LastName"] = ((TextBox)rRow.FindControl("txtLast")).Text;
OneDataRow["City"] = ((TextBox)rRow.FindControl("txtCity")).Text;
OneDataRow["Active"] = ((CheckBox)rRow.FindControl("Active")).Checked;
}
}
As noted I suppose you could drop in a "copy" button, and ONLY persist + save the row index, and then have a paste button - this would allow a cut + paste between any rows, and not be limited to just new rows. (but, that would allow the user quite easy to over-write a existing row - again UI overload from user training point of view.
The above trick is quite slick, since any new rows, any edits are sent back to the database in one simple Update operation. (and the provider is smart - if a row was not touched or changed, then sql update statements are not generated.
This whole trick works due to persisting the table in ViewState. Be warned, if you have a datapager, then you would have to call GridToTable in such navigation, or in fact execute a save command.
Also note how we picked up the .parent.parent (grid row) and again did not bother with teh GV event model. And without a gazilion template stuff, we also saved world poverty in terms of not having to mess with mutiple templates.
In fact, for any grid beyond the above, I use the exact same above approch, but perfer a ListView. The reason is that you can just drag + drop in standard asp.net controls, and you don't have to needless surround them with "item template" which again is too much work and effort.

How to add Delete link in GridView while adding new row from C#?

GridView contains ShowDeleteButton CommandField along with other textbox fields.
I'm adding new row to this grid in C# that is adding new textboxes for each newly added row. How to add Delete link while adding new row?
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" OnRowDataBound="Gridview1_OnRowDataBound"
OnRowDeleting="Gridview1_RowDeleting" AutoGenerateColumns="false" ShowHeaderWhenEmpty="True" EmptyDataText="No Record Available">
<asp:TemplateField HeaderText="Question">
<asp:TextBox ID="txtQuestion" runat="server" Text='<%# Eval("Question") %>'></asp:TextBox>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:TextBox ID="txtAnswer" ReadOnly="true" Enabled="false" runat="server" Text='<%# Eval("Answer") %>'></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAddNewQuestionnaire" runat="server" Text="Add New Row" OnClick="btnAddNewQuestionnaire_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
private void AddNewRow()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Question", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Answer", typeof(String)));
foreach (GridViewRow row in Gridview1.Rows)
{
TextBox txtQuestion = (TextBox)row.FindControl("txtQuestion");
TextBox txtAnswer = (TextBox)row.FindControl("txtAnswer");
dr = dt.NewRow();
dr[0] = txtQuestion.Text;
dr[1] = txtAnswer.Text;
dt.Rows.Add(dr);
}
dt.Rows.Add(dt.NewRow());
dt.Rows[dt.Rows.Count - 1]["Question"] = "";
dt.Rows[dt.Rows.Count - 1]["Answer"] = "";
dt.AcceptChanges();
Gridview1.EditIndex = dt.Rows.Count - 1;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
I recommend that you simple add the delete button to each row. That way the user can easy delete a row.
I also recommend that you load the grid one time with the datatable, and then add the row to the datatable - NOT the grid.
I could write tuckloads of advantages of this approach. But some advantages are:
user does not get presented with multiple UI
user can edit any row on the grid - not have to hit edit, or save
a single un-do button can un-do all changes
a single SAVE button in ONE operation can save the WHOLE TABLE and change back to database
Your code to add a row, and the code to setup and create the database are seperate. This means that you can change the data table, or even have the source of the table come from sql server. And as noted, this also allows you to save the WHOLE table. The result is the user can edit one rows, many rows - tab around MUCH like a excel spreadsheet. When done, they can:
hit save - all data back to database
hit un-do - un-do all their edits
hit + (add row) - add a new row to edit
hit delete key - it will delete the row in question (but UN-DO STILL ACTIVE!!!).
so we have a far more pleasant way to edit.
And thus, I suggest you don't use the built in delete button. Drop in your own button - it will look nicer anyway. (and thus no edit button required either!!!!).
So, here is our markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/Content/uncheck1.jpg" Height="35px" Width="45px"
OnClick="ImageButton1_Click"
MyRowID = '<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question">
<ItemTemplate>
<asp:TextBox ID="txtQuestion" runat="server" Text='<%# Eval("Question") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:TextBox ID="txtAnswer" runat="server" Text='<%# Eval("Answer") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnAddNewQuestionnaire" runat="server" Text="+Add New Row" OnClick="btnAddNewQuestionnaire_Click" />
When you drop the button (I used a image button), then in the code editor do this:
Note how RIGHT after you hit "=" then intel-sense pops up - choose create new event. It looks like NOTHING occurs, but if you flip over to code behind, you see a code sub was generated. You can't double click on the controls inside the grid, but you CAN create a event click for a button - or in fact any event for a standard asp.net control this way.
I also to save world poverties also added a custom attribute to that button called MyRowID - this will set the row index for that button.
Since the add new row button is OUTSIDE of the grid, then we can just double click on that button, and jump to the code behind.
Now, our code looks like this:
private DataTable MyTable = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadGrid();
ViewState["MyTable"] = MyTable;
}
else
MyTable = ViewState["MyTable"];
}
public void LoadGrid()
{
MyTable.Columns.Add(new DataColumn("Question", typeof(string)));
MyTable.Columns.Add(new DataColumn("Answer", typeof(string)));
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
protected void btnAddNewQuestionnaire_Click(object sender, EventArgs e)
{
DataRow MyRow = MyTable.NewRow;
MyRow("Question") = "my question";
MyRow("Answer") = "my ans";
MyTable.Rows.Add(MyRow);
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender;
int RowID = btn.Attributes.Item("MyRowID");
MyTable.Rows(RowID).Delete();
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
Note VERY carefull - we added a MyTable to the form class. Thus we have a persited table, and we operate against that table.
In fact, the EXACT same above desing can be used if the data came from SQL server. And not only MORE amazing, but we can NOW thus SAVE + SEND the whole table BACK to sql server in one update operation. (you just loop the grid, put values back into table, and execute one save).
And the above has no messy edit button to edit a row. and I suppose we COULD add for extra marks a delete conformation box - the user if they bump or hit delete button, they would get a confirm dialog box. That code could be this:
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/Content/uncheck1.jpg" Height="35px" Width="45px"
OnClick="ImageButton1_Click"
MyRowID = '<%# Container.DataItemIndex %>'
OnClientClick="return confirm('Delete this row?');"/>
So now when you hit delete row, you get this:
If you click ok - it deletes - cancel - nothing occurs.
So, you can save a LOT of code and complexity here with:
Persist the data table
Pass the row ID with the button
use the intel-sense trick to wire up a separate and specific button event code.
As noted, this whole above process would ALSO work if you load the table with data from sql server - the REST of the code "as is" will work.
And to save the data back to sql server, then you can as noted:
Pull data from grid back to that persisted table. And then with a data adaptor, ONE update command will send all changes back to sql server.

How can insert values into gridview rows ? ASP.NET ,C#

My question is how can i insert values into gridviews rows.Basically I have created a gridview in which i bound the footer and i want to insert values in the footer.I have create a 'textboxs','dropdownlist' and 'checkboxes'.I want when i insert value and press "Insert" button then values shown in the gridview and again i insert value and press button then show inserted values in the gridview.Here is my gridview image
and i also want to edit and delete rows as well.Here is my code :
aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="104px" ShowFooter="True" Width="463px"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:TemplateField HeaderText="Column Name">
<FooterTemplate>
<asp:TextBox ID="name" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data Type">
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Allow Null">
<FooterTemplate>
<asp:CheckBox ID="allow_null" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Primary Key">
<FooterTemplate>
<asp:CheckBox ID="primary" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my aspx.cs code :
protected void Button1_Click(object sender, EventArgs e)
{
string name = TextBox1.Text;
string type = DropDownList1.Text;
string allow=Null.Text;
string primary = Primary.Text;
name = ((TextBox)GridView1.FooterRow.FindControl("TextBox2")).Text;
type = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
allow = ((CheckBox)GridView1.FooterRow.FindControl("allow_null")).Text;
primary = ((CheckBox)GridView1.FooterRow.FindControl("primary")).Text;
}
To use the GridView in this way, with input fields in the footer and a Insert Button that is outside the GridView, you need to make a manual Insert.
I don't know how you perform an Insert using the EF model as I don't currently use it. I guess you could say the "old" way is to use an instance of SqlConnection and SqlCommand. You would use code similar to this inside your Button Click event:
// This is VB. C# is similar, you will have to convert where needed
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.CommandType = // Typically Text or StoredProcedure as needed
command.Parameters.AddWithValue("#parameter_name1", some_value_1)
command.Parameters.AddWithValue("#parameter_name2", some_value_2)
.
.
.
command.ExecuteNonQuery()
End Using
End Using
queryString is your sql INSERT statement or a stored procedure
command.Parameters is a collection of replaceable parameter in your INSERT statement or Stored Proc.
Addendum
A Gridview is a Data bound control so typically when you use a gridview it's bound to some backing data source. If you are not using a database then you are using some other construct.
If you are using, for example, a DataTable, you would add the new rows and columns to the DataTable using its row and column methods and then rebind the DataTable to the Gridview. You don't add rows and columns directly to a GridView.
See this other SO answer by JonH for an example
In case this helps this is based on the ASPSnippets but modified to be more like you might need. Note that instead of using a DataTable I am using a List where "Row" is a class. It is somewhat a matter of personal preference which one you use. The "Row" class is:
[Serializable]
public class Row
{
public string FieldName { get; set; }
public string FieldType { get; set; }
public Boolean FieldNullible { get; set; }
public Boolean FieldPrimaryKey { get; set; }
}
My names are different from your names. Note that the ASPSnippets sample does not use TemplateFields so I am not. I am not sure if you need to make the "allow"
and/or "primary" fields Boolean so I did not process them in the form. So the ASP.Net form I have is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="104px" Width="463px"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:BoundField DataField="FieldName" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="FieldType" HeaderText="Type" ItemStyle-Width="120" />
</Columns>
</asp:GridView>
<br /><asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<br /><asp:TextBox ID="txtName" runat="server" />
<br /><asp:Label ID="Label2" runat="server" Text="Type:"></asp:Label>
<br /><asp:TextBox ID="txtType" runat="server" />
<br /><asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
The code-behind is:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
return;
List<Row> Rows = new List<Row>();
ViewState["Rows"] = Rows;
BindGrid();
}
protected void BindGrid()
{
GridView1.DataSource = (List<Row>)ViewState["Rows"];
GridView1.DataBind();
}
protected void Insert(object sender, EventArgs e)
{
List<Row> Rows = (List < Row >)ViewState["Rows"];
Row r = new Row();
r.FieldName = txtName.Text.Trim();
r.FieldType = txtType.Text.Trim();
Rows.Add(r);
ViewState["Rows"] = Rows;
BindGrid();
txtName.Text = string.Empty;
txtType.Text = string.Empty;
}
One thing I do not like is that the GridView does not show until there is data in it. I assume you can fix that.
This does not implement the editing and deleting.

How to get cell value in RowUpdating Event GridView?

I want to obtain the new value of a cell in the gridview rowUpdating event:
roles.RoleName = gvRoles.Rows[e.RowIndex].Cells[GetColumnIndexByName(row, "RoleName")].Text;
But the value is empty.
I have checked e.NewValues which is an ordered Dictionary. It contains the new changed value. How do I retrieve the new values for update?
aspx design is:
<asp:GridView ID="gvRoles" DataKeyNames="RoleId" runat="server"
AutoGenerateColumns="False" GridLines="Vertical" CssClass="table
table-striped table-bordered" AutoGenerateEditButton="True"
OnRowCancelingEdit="gvRoles_RowCancelingEdit" OnRowUpdating="gvRoles_RowUpdating"
OnRowEditing="gvRoles_RowEditing">
<Columns>
<asp:BoundField DataField="RoleId" HeaderText="RoleId" ReadOnly="True" />
<asp:BoundField DataField="RoleName" HeaderText="RoleName" ReadOnly="false" />
<asp:BoundField DataField="Role_Description" HeaderText="Role Description" ReadOnly="false" />
<asp:TemplateField HeaderText="RoleStatus">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" SelectedValue='<%# Bind("Role_Status") %>' >
<asp:ListItem>True</asp:ListItem>
<asp:ListItem>False</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRoleStatus" runat="server"
Text='<%# Bind("Role_Status") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The easiest way which i found out is to discovered e.NewValues. As I mentioned above it is an ordered dictionary and only i need to manage it.
I need to retrieve new values from this dictionary, which is done i this way.
if (!string.IsNullOrEmpty(e.NewValues["RoleName"].ToString()))
{
roles.RoleName = e.NewValues["RoleName"].ToString();
}
if you have template field it also work for it;
if (!string.IsNullOrEmpty(e.NewValues["Role_Status"].ToString()))
{
roles.Role_Status = Convert.ToBoolean(e.NewValues["Role_Status"].ToString());
}
This is the easiest thing I ever discovered. before that i want just using Find control and casting and then retrieving all lot code.
There is also e.OldValues ordered dictionary. Every one can use it to compare the new value with old ones. If values are same they could notify user to change the value(give new cell value).
GridViewRow row = (GridViewRow)gvRoles.Rows[e.RowIndex];
TextBox textRName = (TextBox)row.Cells[1].Controls[0];
string rname=textRname.Text;
Try This:
protected void gvRoles_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvRoles.Rows[e.RowIndex];
TextBox txtBox= (TextBox)(row.Cells[1].Controls[0]);
if(txtBox!=null)
{
String str = txtBox.Text;
}
}
After searching long and hard I found a great article that solved my issue. Take a look at the page load if you are binding on post back then the values get updated before you are able to access them.
Follow this link for more details --> https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/
The return data type ICollection is a bit tricky. Would have preferred a different data type than a string array but this was simplest direct conversion.
// grabs column headers
String[] keyStrings = new string[e.NewValues.Count];
System.Collections.ICollection keys = e.NewValues.Keys;
keys.CopyTo(keyStrings, 0);
// grabs edit row values
String[] valuesStrings = new string[e.NewValues.Count];
System.Collections.ICollection values = e.NewValues.Values;
values.CopyTo(valuesStrings, 0);
The end result here has two string arrays values and keys which can then be indexed, where the column header has the same index value as the cell value of the edited row.

gridview column value manipulated

my intention was to switch form an int-represented month value
(as it is in database table)
convert it (to display in GridView) as string(month name)
and return it back to database as int (covert back to original type, int-represented month).
these are the relevant elements in my GridView,
<asp:GridView ID="GV_DaysPerMonth" runat="server" DataSourceID="dsWorkDayPerMonth"
AutoGenerateColumns="False" DataKeyNames="recordID" AllowPaging="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Font-Names="arial" PageSize="12"
OnRowDataBound="GV_DaysPerMonth_RowDataBound"
OnRowEditing="GV_DaysPerMonth_RowEditing"
OnRowUpdating="GV_DaysPerMonth_RowUpdating">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="חודש" ControlStyle-Width="100" HeaderStyle-Width="120" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Eval("theMonth")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TBX_theMonth" runat="server" Text='<%# Bind("theMonth")%>' />
</EditItemTemplate>
<asp:GridView ID="GV_DaysPerMonth" runat="server" DataSourceID="dsWorkDayPerMonth"
AutoGenerateColumns="False" DataKeyNames="recordID" AllowPaging="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Font-Names="arial" PageSize="12"
OnRowDataBound="GV_DaysPerMonth_RowDataBound"
OnRowEditing="GV_DaysPerMonth_RowEditing"
OnRowUpdating="GV_DaysPerMonth_RowUpdating">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Current Month" ControlStyle-Width="100" HeaderStyle-Width="120" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Eval("theMonth")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TBX_theMonth" runat="server" Text='<%# Bind("theMonth")%>' />
</EditItemTemplate>
i was tring using these Helper methods From code Behind
public static CultureInfo ILci = CultureInfo.CreateSpecificCulture("he-IL");
public static string GetMonthName(int mInt)
{
DateTime fullDate = new DateTime(2012, mInt, 2);
string[] tempDayArray = fullDate.ToString("MMMM", ILci).Split(' ');
return tempDayArray[0];
}
public static int GetMonthAsInt(string mStr)
{
return DateTime.ParseExact(mStr, "MMMM", ILci).Month;
to achieve this simple task but had few errors i would like to have an example to how is the right way to achieve it.
i thought it's simple cause displaying int via
<%# manipulation Function( Eval("columnName")) %>
would "just work"
but it got too complicated for me as newb
when trying it with Bind("columnName")
i was wrong by assuming the value was inside Cells[1] when it was actually in Cells[0]
so i do have it in normal mode
and also in Edit mode though not editble but via Label as in view mode instead of a TextBox
protected void GV_DaysPerMonth_RowDataBound(object sender, GridViewRowEventArgs e)
{
RowNum = GV_DaysPerMonth.Rows.Count;
GridViewRow CurRow = e.Row; // Retrieve the current row.
if (CurRow.RowType == DataControlRowType.DataRow)
{
bool isntEmptyMonth = string.IsNullOrEmpty(e.Row.Cells[0].Text) == false;
if (isntEmptyMonth)
{
e.Row.Cells[1].Text = RobCS.RDates.GetMonthName(Convert.ToInt32((e.Row.Cells[0].Text)));
}
}
}
so i think it might be the **missing handler for the edit mode** ?
This is what you would do to get a string Month name from an int:
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
More info here:
Best way to turn an integer into a month name in c#?
For converting month number into month name in sql server, look here:
Convert Month Number to Month Name Function in SQL
---- EDIT
OK, on RowDataBound, you would want to convert int to string, so it would be something like:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the month name. When you GridView is bound for the first time, you
// will bind the month number, which you can get in e.Row.Cells[1].Text. If
// Cells[1] does not work, try Cells[2], till you get the correct value. The
// convert the int to month name and assign it to the same Cell.
e.Row.Cells[1].Text = GetMonthNameFromInt(e.Row.Cells[1].Text)
}
}
On Row_updating, you want to convert the month name to int again, and then update you dataset (or save to the database)
protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Update the values.
GridViewRow row = GridView.Rows[e.RowIndex];
var monthName = ((TextBox)(row.Cells[1].Controls[0])).Text;
var monthNumber = GetMonthNumber(monthName);
// code to update your dataset or database with month number
//Reset the edit index.
GridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
Page class:
private static CultureInfo culture = CultureInfo.CreateSpecificCulture("he-IL");
public static string GetMonthName(string monthNum)
{
return culture.DateTimeFormat.GetMonthName(Convert.ToInt32(monthNum));
}
GridView:
<ItemTemplate>
<%# GetMonthName(Eval("theMonth").ToString())%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlMonth" runat="server" SelectedValue='<%# Bind("theMonth")%>'>
<asp:ListItem Value="1" Text="תשרי"></ListItem>
etc...
</asp:DropDownList>
</EditItemTemplate>
In your EditTemplate have a DropDownList with ListItems: value="1" Text="תשרי" etc.. so that it's the month number that's passed to your data layer for edits.

Categories

Resources