Enable and disable link button on gridview - c#

I wants to enable or disable linkbutton on some rows of gridview based on condition.. Can i enable linkbutton on one row and disable it on another row of same grid view ??my code is here
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd12 = new SqlCommand("Select testsession_status from student_vs_testsession_details where testsession_id='" + v_testid.Text + "' ", con12);
SqlDataReader dr12 = cmd12.ExecuteReader();
while (dr12.Read())
{
string test_status = dr12[0].ToString();
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
foreach (GridViewRow row in GridView1.Rows)
{
if (v_testtype == "Theory Test" && test_status == "Completed")
{
lnk2.Visible = true;
}
else
{
lnk2.Visible = false;
}
}
}

Yes you can easily do it in RowdataBound Event, but you have used lnk2.Visible property in your code.
you may be using Visible property for another requirement but just want to confirm you that it is used to show/hide the Linkbutton only. To enable/disble a Linkbutton, use Enabled property of Linkbutton. as:
lnk2.Enabled = true;// to enable linkbutton.
lnk2.Enabled = false;// to disable linkbutton.
If You want to do it using rowindex, then you can e.Row.RowIndex to find the current row index inside 'RowDatabound` event of gridview. as:
if(e.Row.RowIndex==2)
{
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
lnk2.Enabled=false;
}
If you want to enable/ disable Linkbutton based on value of some other column in the same row, then you can do the same inside Rowdatabound event. as:
string Namecolumnvalue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if(Namecolumnvalue =="Disable")
{
lnk2.Enabled=false;
}
else{
lnk2.Enabled=true;
}

--------aspx page code---------
<asp:GridView ID="gvLibrary" runat="server" AutoGenerateColumns="False" Width="100%" DataKeyNames="LibMstRefNo"
EmptyDataText="No Client Found" CssClass="table table-striped table-bordered" OnRowDataBound="gvLibrary_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Issue">
<ItemTemplate>
<asp:LinkButton ID="lnkIssue" runat="server" Text="Issue" OnClick="lnkIssue_Click"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Receive">
<ItemTemplate>
<asp:LinkButton ID="lnkReceive" runat="server" Text="Receive" OnClick="lnkReceive_Click" OnClientClick="return confirm('Are you Sure?')"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
------------aspx.cs page code------------------
protected void gvLibrary_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string nbps = e.Row.Cells[8].Text;
if(nbps== " ")
{
nbps = "";
}
else
{
nbps = e.Row.Cells[8].Text;
}
if (nbps == "")
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = true;
btn1.Enabled = false;
btn1.ForeColor = System.Drawing.Color.Red;
}
else
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = false;
btn.ForeColor = System.Drawing.Color.Red;
btn1.Enabled = true;
}
}
}

Related

Dynamically add rows to GridView which contain web controls in ASP.NET

Hi I'm having a great issue because I don't know where to start. I need to create a Gridview which has to buttons below it, a "Create Row" button and a "Delete Row" button. I want that everytime the "Create Row" button is pressed a new row to be added to the GridView, however the main problem is that I need that new row to be filled with different controls such as DropDownLists and TextBox, but I have no idea of how to do it properly. Here is an image of how I want the GridView to be:
Each row has 2 dropdown lists, two textbox and a button
I know that I need to bind the GridView to a data source such as a dataTable, but I have no idea if that will work with controls such as TextBox or DropDownLists. Sorry if I don't add any code because I really don't know where to start. Thank you.
If i understood it right u can follow this:
Create Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand" DataKeyNames="RowNumber">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" Visible="false" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect"
ToolTip="Select To Delete This Row" />
<asp:Label runat="server" ID="lblId" Text='<%# Bind("Id") %>'
Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstEntry" Visible="false" Text='<%# Eval("FirstEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlFirstEntry" runat="server" ClientIDMode="Static" CssClass="ddlFirstEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondEntry" Visible="false" Text='<%# Eval("SecondEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlSecondEntry" runat="server" ClientIDMode="Static" CssClass="ddlSecondEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFirstTextBox" runat="server" Text='<%# Eval("FirstTextBox") %>'
CssClass="txtFirstTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFSecondTextBox" runat="server" Text='<%# Eval("SecondTextBox") %>'
CssClass="txtSecondTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in Code behind in Page_Load call this method
private void InitializeGrid()
{
try
{
ViewState["applicationDetail"] = null;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Id", typeof(int)),
new DataColumn("FirstEntry", typeof(string)),
new DataColumn("SecondEntry",typeof(string)),
new DataColumn("FirstTextBox", typeof(string)),
new DataColumn("SecondTextBox", typeof(string))
});
DataRow drRow = dt.NewRow();
drRow["Id"] = 1;
drRow["FirstEntry"] = string.Empty;
drRow["SecondEntry"] = string.Empty;
drRow["FirstTextBox"] = string.Empty;
drRow["SecondTextBox"] = string.Empty;
dt.Rows.Add(drRow);
ViewState["applicationDetail"] = dt;
GridView1.DataSource = ViewState["applicationDetail"];
}
catch (Exception ex)
{
throw;
}
}
InitializeGrid();
GridView1.DataBind();
On GridView1_RowDataBound Bind All your drop down controls
upto this will create a grid with one empty row.
Now On Add Button Click do following
protected void btnNewRow_Click(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
}
catch (Exception ex)
{
throw ex;
}
}
private void AddNewRowToGrid()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values _lblGuestId
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["FirstEntry"] = ddl1.SelectedValue;
dtCurrentTable.Rows[i - 1]["SecondEntry"] = ddl2.SelectedValue;
dtCurrentTable.Rows[i - 1]["FirstTextBox"] = txt1.Text;
dtCurrentTable.Rows[i - 1]["SecondTextBox"] = txt2.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["applicationDetail"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
catch (Exception ex)
{
throw ex;
}
}
private void SetPreviousData()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
ddl1.SelectedValue = dtCurrentTable.Rows[i]["FirstEntry"].ToString();
ddl2.SelectedValue = dtCurrentTable.Rows[i]["SecondEntry"].ToString();
txt1.Text = dtCurrentTable.Rows[i]["FirstTextBox"].ToString();
txt2.Text = dtCurrentTable.Rows[i]["SecondTextBox"].ToString();
rowIndex++;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
For Deleting
On GridView1_RowCommand when check box is checked get row indexes of all the checked check box rows and keep it in some session or application variable.
On delete button click use that variable for deleting the rows.
I hope your problem will be solved.
As per your comment i am adding GridView1_RowDataBound for drop down bindings
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DropDownList ddl1 = (e.Row.FindControl("ddlFirstEntry") as DropDownList);
Label lbl1 = (e.Row.FindControl("lblFirstEntry") as Label);
DropDownList ddl2 = (e.Row.FindControl("ddlSecondEntry") as DropDownList);
Label lbl2 = (e.Row.FindControl("lblSecondEntry") as Label);
ddl1.Items.Clear();
ddl1.AppendDataBoundItems = true;
ddl1.Items.Add(new ListItem("-Select-", "-1"));
ddl1.DataSource = ViewState["ddl1datasourse"];
ddl1.DataTextField = "Value";
ddl1.DataValueField = "Id";
ddl1.DataBind();
if (ddl1.SelectedValue != string.Empty && lbl1.Text != null)
ddl1.SelectedValue = lbl1.Text.Trim();
else
ddl1.SelectedValue = "-1";
ddl2.Items.Clear();
ddl2.AppendDataBoundItems = true;
ddl2.Items.Add(new ListItem("-Select-", "-1"));
ddl2.DataSource = ViewState["ddl2datasourse"];
ddl2.DataTextField = "Value";
ddl2.DataValueField = "Id";
ddl2.DataBind();
if (ddl2.SelectedValue != string.Empty && lbl2.Text != null)
ddl2.SelectedValue = lbl2.Text.Trim();
else
ddl2.SelectedValue = "-1";
}
catch (Exception ex)
{
throw ex;
}
}

selecting the row in gridview using row index

protected void select_click(object sender, GridViewCommandEventArgs e)
{
try
{
DBLibrary db = new DBLibrary();
int index = Convert.ToInt32(e.CommandArgument);
* string FeeId = gridv1.Rows[index].Cells[1].Text;*
if (e.CommandName == "Select")
{
string str = "SELECT AnuFeeMaster.FeeId ,AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.FeeId ='" + FeeId + "')";
SqlDataReader dr = db.ExecuteReader(str);
while (dr.Read())
{
Session["name"] = dr["sname"].ToString();
Session["id"] = dr["StudentId"].ToString();
Session["mth"] = dr["Month"].ToString();
Session["yr"] = dr["Year"].ToString();
Session["tot"] = dr["FeeAmount"].ToString();
}
}
}
catch { }
}
Above is my code what i used to access that i am not getting the value r data from dat Please suggest me, * mark which i used that show where i am getting the error
create proper grid rowcommand Event
aspx code
<asp:GridView ID="Gv" runat="server" AllowPaging="true" OnRowCommand="Gv_RowCommand" PageSize="10" EmptyDataText="No Records Found !">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="20%">
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandArgument='<%#Eval("Demo_Code") %>' CommandName="select" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Coulmn1" HeaderText="Coulmn2" />
<asp:BoundField DataField="Coulmn2" HeaderText="Coulmn2" />
</Columns>
</asp:GridView>
aspx.cs Code
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
}
}
You should properly use RowCommand event of gridview.
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
You can catch the button click event like below:
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

How to fill selected value to a grid from another grid?

I have a Grid1 with check box, Now I want to store Grid1 selected values into another grid grid2. How can I do this?
My Grid1 is
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" DataKeyNames="ShiftID"
Width="177px" onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChbGrid" runat="server" oncheckedchanged="ChbGrid_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChbGridHead" runat="server" AutoPostBack="True"
Font-Bold="True" oncheckedchanged="ChbGridHead_CheckedChanged" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Gridview2 is
<asp:GridView ID="GridView2" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2">
</asp:GridView>
I have some function
protected void ChbGrid_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkstatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)checkstatus.NamingContainer;
}
protected void ChbGridHead_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkheader = (CheckBox)GridView1.HeaderRow.FindControl("ChbGridHead");
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if (chkheader.Checked == true)
{
chkrow.Checked = true;
{
}
}
else
{
chkrow.Checked = false;
}
}
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
}
What changes I should made to get my expected output. My GridView1 conatins ShiftID,ShiftName,ShiftTime and Date. How to generate query to dispaly selected Gridview1 item in Griview2
Write this in Source file
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected records" OnClick="GetSelectedRecords" />
On the click of the Button the following event handler is executed. A loop is executed over the GridView Data Rows and CheckBox is referenced.
protected void GetSelectedRecords(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
string name = row.Cells[1].Text;
string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
dt.Rows.Add(name, country);
}
}
}
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
For more information us this links
GridView with CheckBox: Get Selected Rows in ASP.Net
Transfer Selected Rows from one GridView to Another in Asp.net

Binding dropdownlist inside gridview edititemtemplate

I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.

why is value not changing in rowdatabound

Why can't i change the value in a specific row in the rowdatabound event of my gridview? the code is entering where the value is set to Test but still shows old value?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="au_id" DataSourceID="SqlDataSource1"
ondatabinding="GridView1_DataBinding" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True"
SortExpression="au_id" />
<asp:BoundField DataField="au_lname" HeaderText="au_lname"
SortExpression="au_lname" />
<asp:BoundField DataField="au_fname" HeaderText="au_fname"
SortExpression="au_fname" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]">
</asp:SqlDataSource>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var customerName = row.Field<String>("au_lname");
if (customerName == "Carson")
{
customerName = "Test";
}
}
}
Because you cannot change the underlying DataSource in RowDataBound(too late). You need to apply your changes to the TemplateFields controls or to the CellCollection of the row(in case of BoundFields or AutogenerateColumns=true):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var customerName = row.Field<String>("au_lname");
if (customerName == "Carson")
{
e.Row.Cells[1].Text = "Test";
}else
{
e.Row.Cells[1].Text = customerName;
}
}
}

Categories

Resources