asp.net gridview editindex - asp.net

Please take a look at this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
}
}
This code-snippet puts an entire gridview-row into the edit mode.
But I need to put only the 3rd and 5th cell (suppose) of a row into edit mode.
How can I do so?
Some may suggest not using edit template. But I am only using code behind to manipulate my data in the gridview like the following:
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridView___Test._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Font-Names="Verdana" Font-Size="Small" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
</asp:GridView>
</div>
</form>
</body>
</html>
code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
ControlCollection cc = gvr.Cells[1].Controls;
TextBox tb = (TextBox)cc[0];
GridView1.EditIndex = -1;
CreateGridView();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
}
And my view is to avoid asp.net scripting as much as possible.
And also what is possible using scripts, must be possible by only code.

see if following helps. i.e. put non editable columns propery InsertVisible to false. Further you can put the following code in GridView1_DataBinding event. remove line GridView1.DataBind(); and just call again GridView1.DataBind(); where you call this method.
private void CreateGridView()
{
GridView GridView1 = new GridView();
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
if (colCount == 3 | colCount == 5)
{
boundField.InsertVisible = true;
}
else
{
boundField.InsertVisible = false;
}
colCount++;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dataTable;
GridView1.DataBind();
}

Related

Creating an ASP.net GridView board (without server connection)

I'm going to create a 4-column, 10-line gridview board. I want to make it using a loop. I do not know what to do with the cs code. I am a beginner and I am practicing as an example. Help please.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
AllowSorting="True"
AllowPaging="True" PageSize="10" onrowdatabound="GridView1_RowDataBound"
ondatabound="GridView1_DataBound" EmptyDataText="NO">
<EmptyDataTemplate>No Data</EmptyDataTemplate>
</asp:GridView>
.aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
{
e.Row.Cells[0].Text = "Complete";
}
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
var str = GridView1.DataKeys[row.RowIndex]["SomeColumnName"];
}
Quick Example:
.aspx code:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create a datatable as a DataSource of your GridView
DataTable dt = new DataTable();
// Add columns
if (dt.Columns.Count == 0)
{
for (int i = 1; i <= 4; i++)
{
dt.Columns.Add("Column" + i);
}
}
// Add rows
for (int i = 1; i <= 10; i++)
{
dt.Rows.Add("Data" + i, "Data" + i, "Data" + i, "Data" + i);
}
// Bind datatable to gridview
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Output:

Asp.net GridView Enabling row selection

I am using GridView in asp.net. I want to select a single data row. I looked for MultiSelect and SelectionMode in property panel, but I can't find it.
So how to enable selecting rows in GridView?
Thanks.
Code Behind
public partial class SearchCourse : System.Web.UI.Page
{
Connection dbCon;
DataTable tbl;
protected void Page_Load(object sender, EventArgs e)
{
dbCon = new Connection();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked) {
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled =false;
txtSubName.Text = "";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) {
comboProgram.Enabled = true;
if (comboProgram.SelectedItem.ToString() == "Foundation Course")
{
comboSemester.Enabled = false;
comboYear.Enabled = false;
}
else {
comboSemester.Enabled = true;
comboYear.Enabled = true;
}
txtSubName.Text = "";
txtSubName.Enabled = false;
}
}
protected void imgBtnSearch_Click(object sender, ImageClickEventArgs e)
{
if (RadioButton1.Checked) {
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectName(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton2.Checked)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem= comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program,year,sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton3.Checked)
{
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectNo(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year, sem;
if (program == "Foundation Course")
{
comboYear.Enabled = false;
comboSemester.Enabled = false;
year = null;
sem = null;
}
else {
comboYear.Enabled = true;
comboSemester.Enabled = true;
year = comboYear.SelectedItem.ToString();
sem = comboSemester.SelectedItem.ToString();
}
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboYear_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboSemester_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled = false;
txtSubName.Text = "";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
GridView Code
<asp:GridView ID="GridView1" CssClass="grid" runat="server" AllowPaging="True"
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
GridLines="Horizontal" EnableViewState="False"
PageSize="5" onselectedindexchanged="GridView1_SelectedIndexChanged" >
<RowStyle CssClass="gridRow" Width="800px" />
<SelectedRowStyle BackColor="#FF0066" ForeColor="White" />
</asp:GridView>
I think the MultiSelect and SelectionMode properties are only available with the VB.NET grid, not in ASP.NET. Bear in mind that all controls in ASP.NET are HTML-in-disguise, so they may be more limited. There is no reason why you can't have a multi-select table, but you have to do the plumbing yourself. So you need to enable row selection, either by handling the RowDataBound event as in
http://forums.asp.net/t/992062.aspx?How+to+select+row+in+gridview+on+click
or else using the MS-provided option as in
http://msdn.microsoft.com/en-us/library/wbk82279(v=vs.100).aspx
Then you need to handle the SelectedIndexChanging event, figure out which row the user clicked on, and handle the row-colouring yourself.
This problem is still actual for me 9 years later.
In As?x code I added SelectedRowStyle and asp:CommandField blocks:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<SelectedRowStyle BackColor="#337ab7" ForeColor="White" />
<Columns>
<asp:CommandField SelectText="Select" ShowSelectButton="True">
<HeaderStyle Width="50px" />
</asp:CommandField>
Code behind:
protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
}
In gridview you have to define an event onselectedindexchanged and onrowdatabound as below:
onselectedindexchanged="GridView1_SelectedIndexChanged" onrowdatabound="GridView1_RowDataBound"
to show the selected row you can use following style in your grid view:
<SelectedRowStyle BackColor="Red" />
in code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
// The seelctButton exists for ensuring the selection functionality
// and bind it with the appropriate event hanlder.
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text
};
selectButton.Font.Underline = false;
selectButton.ForeColor = Color.Black;
e.Row.Cells[0].Controls.Add(selectButton);
//e.Row.Attributes["OnClick"] =
// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
note: you can find the event in event window.

SelectedIndexChanged not firing in ascx?

I use masterpage.In ascx page my selectedindexchange event not firing.
This is my code:
My ascx :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FilterList.ascx.cs"
Inherits="F8.B2B.WEB.UserControls.Common.FilterList.FilterList" %>
<asp:UpdatePanel UpdateMode="Always" runat="server">
<ContentTemplate>
<div id="filterList" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
My ascx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
createFilterLists();
}
}
private void createFilterLists()
{
ListBox dpList = new ListBox()
{
ID = ControlID
};
dpList.Items.Clear();
if (lst_ListItem != null)
{
foreach (ListItem item_ in lst_ListItem)
{
dpList.Items.Add(item_);
}
dpList.Items[0].Selected = true;
dpList.AutoPostBack = true;
dpList.EnableViewState = true;
dpList.SelectedIndexChanged += new EventHandler(myListBox_SelectedIndexChanged);
filterList.Controls.Add(dpList);
}
}
protected void myListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// might be entered on change
}
Because your list box is dynamically generated by code, you need to add it in every page load even if it is a postback.
Create dynamic controls and add event handlers in the OnInit event
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControls();
myDataGrid.SomeEventHandler += new ...
}
Bind data and fill controls in the OnLoad event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillControls();
myDataGrid.DataSource = somedatasource;
myDataGrid.DataBind();
}
}
private void CreateControls()
{
ListBox dpList = new ListBox()
{
ID = ControlID
};
dpList.AutoPostBack = true;
dpList.EnableViewState = true;
dpList.SelectedIndexChanged += new EventHandler(myListBox_SelectedIndexChanged);
filterList.Controls.Add(dpList);
}
private void FillControls()
{
dpList.Items.Clear();
if (lst_ListItem != null && lst_ListItem.Count > 0)
{
foreach (ListItem item_ in lst_ListItem)
{
dpList.Items.Add(item_);
}
dpList.Items[0].Selected = true;
}
}

modify datarow value for a specific gridview column

how would i change the value IBM to something arbitrary like Cisco in one of the gridview events listed?
there can be varying columns in the dynamic gridview so would be nice to address the column by name.
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("TestTable");
dt.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("customername") });
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Microsoft";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2[0] = "2";
dr2[1] = "IBM";
dt.Rows.Add(dr2);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
}
}
This won't work when AutogenerateColumns is set to true(default). You need to add the columns programmatically or declaratively(in aspx markup). Then you can use a TemplateField with a Control like Label that you can reference in codebehind:
For example:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" runat="server">
<Columns>
<asp:TemplateField HeaderText="Customer">
<ItemTemplate>
<asp:Label ID="LblCustomer" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
RowDataBound is perfect(for almost everything):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) {
var row = ((DataRowView)e.Row.DataItem).Row;
var lblCustomer = (Label)e.Row.FindControl("LblCustomer");
var customerName = row.Field<String>( "customername" );
if(customerName == "Microsoft") {
customerName = "Cisco";
}
lblCustomer.Text = customerName;
}
}
Edit: Ok, never needed to do such. But actually you can change the Microsoft values to Cisco even with AutoGenerateColumns set to true.
DataBinding event is triggered before the GridView is databound. If you change the datasource before it's bound to grid, you'll be able to modify it:
protected void GridView1_DataBinding(object sender, EventArgs e)
{
var tbl = (DataTable)((GridView)sender).DataSource;
var msRows = tbl.AsEnumerable()
.Where(r => r.Field<String>("customername") == "Microsoft")
.Select(r => r);
foreach(DataRow msRow in msRows) {
msRow[ "customername" ] = "Cisco";
}
}
Note: of course you can also use a simple loop instead of LINQ

asp.net - GridView dynamic footer row creation problem

I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.

Resources