I have a grid view where data is dyanmically added. I need an onRowCommand where the selected row will be deleted. I need the row to be deleted only from the grid view.
protected void LoadDataTable()
{
string header = lblHeader.Text;
string aa = tv.SelectedNode.Parent.Value;
string child = tv.SelectedNode.Text;
string parent = tv.SelectedNode.Parent.Text;
var dt = new DataTable();
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("TargetGLId");
dt.Columns.Add("TargetHead");
dt.Columns.Add("Parent");
dt.Columns.Add("Header");
foreach (GridViewRow row in gvBudgetSetup.Rows)
{
var lblheader = (Label)row.FindControl("lblHeader");
var lblparticular = (Label)row.FindControl("lblParticular");
var lblGlId = (Label)row.FindControl("lblGLId");
var lblparent = (Label)row.FindControl("lblParent");
var dr = dt.NewRow();
dr["TargetHead"] = lblparticular.Text;
dr["TargetGLID"] = lblGlId.Text;
dr["Parent"] = lblparent.Text;
dr["Header"] = lblHeader.Text;
dt.Rows.Add(dr);
}
var dr1 = dt.NewRow();
dr1["TargetHead"] = child;
dr1["TargetGLID"] = tv.SelectedValue;
dr1["Parent"] = parent;
dr1["Header"] = header;
dt.Rows.Add(dr1);
gvBudgetSetup.DataSource = null;
gvBudgetSetup.DataBind();
gvBudgetSetup.DataSource = dt;
gvBudgetSetup.DataBind();
}
I have tried this code to delete the row but it is not working.
protected void gvBudgetSetup_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete1")
{
// gvBudgetSetup.DeleteRow(e.Row.RowIndex);
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
}
}
This is the Gridview created. The gridview is not connected to any database. The data in the gridview is added from the back-end codes.
<asp:GridView ID="gvBudgetSetup" runat="server" CssClass="table1" AutoGenerateColumns="false" ShowFooter="true" OnSelectedIndexChanged="gvBudgetSetup_SelectedIndexChanged"
ShowHeaderWhenEmpty="true" OnRowDataBound="gvBudgetSetup_RowDataBound" OnRowCommand="gvBudgetSetup_RowCommand" OnRowDeleting="gvBudgetSetup_RowDeleting" Width="100%">
<FooterStyle CssClass="GridFooter" />
<RowStyle CssClass="GridItem" />
<columns>
<asp:TemplateField HeaderText="Sn">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GL Id">
<ItemTemplate>
<asp:Label ID="lblGLId" runat="server" Text='<%# Bind("TargetGLID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header">
<ItemTemplate>
<asp:Label ID="lblHeader" runat="server" Text='<%# Bind("Header") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Parent">
<ItemTemplate>
<asp:Label ID="lblParent" runat="server" Text='<%# Bind("Parent") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Child">
<ItemTemplate>
<asp:Label ID="lblParticular" runat="server" Text='<%# Bind("TargetHead") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Delete" CommandName="Delete1"
ID="lnkDelete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</columns>
<EmptyDataTemplate>
"There are no data to display..."
</EmptyDataTemplate>
</asp:GridView>
Better way to do is have a flag in the data source that one row is flagged(deleted) and bind it again. To delete a datarow from a GridViewEvent, you have to re bind the datasource again.
Introduce a Flag column in your data source
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//Update the flag in datasource using the CommandArgument value
//Bind the datasource again.
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int getRowIndex = gvr.RowIndex;
gvBudgetSetup.DeleteRow(getRowIndex);
Use this updated code
Related
I have following grid in asp.net
<asp:GridView ID="grdDWlocations" CssClass="table table-hover table-striped" runat="server" GridLines="None" ShowHeaderWhenEmpty="True"
EmptyDataText="No data found..." AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="" Visible="true">
<HeaderTemplate>
<asp:CheckBox ID="allDWlocchk" runat="server" Checked="true" Width="10px" onclick="CheckAllgrdReqDW(this)"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk_DWlocReq" runat="server" Checked="true" Width="5px" OnCheckedChanged="chk_Req_CheckedChangedDW_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lbl_DWCode" runat="server" Text='<%# Bind("Ml_loc_cd") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lbl_DWDescription" runat="server" Text='<%# Bind("Ml_loc_desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to assign value for "chk_DWlocReq" in code behind
like this
foreach (GridViewRow dgvr in grdDWlocations.Rows)
{
(CheckBox)dgvr.FindControl("chk_DWlocReq")=true;
}
but above one not valid, how can this do properly ?
I believe your code must be changed to:
foreach (GridViewRow dgvr in grdDWlocations.Rows)
{
((CheckBox)dgvr.FindControl("chk_DWlocReq")).Checked=true;
}
Use this:
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
CheckBox myCheckBoxID = row.FindControl("myCheckBoxID") as CheckBox;
}
myCheckBoxID.Checked = true;
}
OR
If you are handling RowDataBound event, it's like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox myCheckBoxID = e.Row.FindControl("myCheckBoxID") as CheckBox;
}
myCheckBoxID.Checked = true;
}
Try the following:
CheckBox checkbox1 = dgvr.FindControl("chk_DWlocReq") as CheckBox;
checkbox1.Checked = true;
I used this code:
ds1.SelectCommand = String.Format("exec myStoredproc");
dv1 = (DataView)ds1.Select(DataSourceSelectArguments.Empty);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (dv1.Table.Rows[i]["ReceiveNotification"].ToString() == "1")
{
((CheckBox)GridView1.Rows[i].FindControl("GV_chkNotification")).Checked = true;
}
else
{
((CheckBox)GridView1.Rows[i].FindControl("GV_chkNotification")).Checked = false;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="301px" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
<%-- <asp:BoundField DataField="StudentDOB" HeaderText="StudentDOB" SortExpression="StudentDOB" />--%>
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/Employee/EmployeeEditPage.aspx?StudentID={0}", Eval("StudentID"))%>'> Edit</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
above is my design:
below I wrote my code for to display the database, which have table departmenttable and another table studenttable to show the values into the grid. in department table I have departmentname(dept_name)
which should come in dropdown inside the gridview..but it showing error..pls help..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(DataBase.GetConnection());
con.Open();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList = (DropDownList)e.Row.FindControl("dept_name");
//bind dropdownlist
DataTable dt = con.GetData("select dept_name from dbo.DepartmentTable");
ddList.DataSource = dt;
ddList.DataTextField = "dept_name";
ddList.DataValueField = "DeptName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["DeptName"].ToString();
con.Close();
GridView1.DataBind();
}
}
}
For binding dropdownlist in GriView first you need to find it by its id. In your sample code, you are trying to find something which is not dropdownlist.
Try this,
DropDownList ddList = (e.Row.FindControl("DropDownList1") as DropDownList);
if(ddList != null)
{
//your code
}
I have a manage Customer table and grid view customer.
I am trying to update grid record. I want when i click edit link records display in table.
I am trying to do it on Grid_Row_command event.
I am getting records on textbox but not able to get selected dropdown record.
Please tell me how to do this.
Here is snapshot of my table & Gridview.
.
Here is my code-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mspl.Web.MobileTracking.BL;
using Mspl.MobileTracking.Model;
namespace Mspl.Web.MobileTracking.UserControls
{
public partial class ManageCustomers : System.Web.UI.UserControl
{
Utility utility;
string result = string.Empty;
User user = new User();
CustomerBL customerBL;
Customer Customer = new Customer();
CustomerBL Customers = new CustomerBL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCountry();
BindCustomer();
}
lblMessage.Text = string.Empty;
}
private void BindStates()
{
utility = new Utility();
var states = utility.GetStates(ddlCountry.SelectedItem.Value);
ddlState.DataSource = states;
ddlState.DataTextField = "Name";
ddlState.DataValueField = "ID";
ddlState.DataBind();
ddlState.Items.Insert(0, "--Select--");
}
private void BindCountry()
{
utility = new Utility();
var countries = utility.GetCountries();
ddlCountry.DataSource = countries.ToList<Country>();
ddlCountry.DataTextField = "Name";
ddlCountry.DataValueField = "ID";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, "--Select--");
}
private void BindDistricts()
{
utility = new Utility();
var districts = utility.GetDistricts(ddlState.SelectedItem.Value);
ddlDistrict.DataSource = districts;
ddlDistrict.DataTextField = "Name";
ddlDistrict.DataValueField = "ID";
ddlDistrict.DataBind();
ddlDistrict.Items.Insert(0, "--Select--");
}
private void BindCustomer()
{
gvCustomer.DataSource = Customers.GetAllCustomers();
gvCustomer.DataBind();
}
protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "displayCustomer")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
hfCustomerId.Value = Convert.ToString(e.CommandArgument);
Label lblCName = (Label)row.FindControl("lblCustomerName");
txtCustomerName.Text = lblCName.Text;
Label lblAdd1 = (Label)row.FindControl("lblAddressLine1");
txtAddressline1.Text = lblAdd1.Text;
Label lblAdd2 = (Label)row.FindControl("lblAddressLine2");
txtAddressline2.Text = lblAdd2.Text;
Label lblPhone = (Label)row.FindControl("lblPhone");
txtPhone.Text = lblPhone.Text;
Label lblMobile = (Label)row.FindControl("lblMobile");
txtMobileNumber.Text = lblMobile.Text;
Label lblCountry = (Label)row.FindControl("lblCountry");
ddlCountry.SelectedIndex = Convert.ToInt32(lblCountry.Text);
Label lblState = (Label)row.FindControl("lblState");
ddlState.SelectedIndex = Convert.ToInt32(lblState.Text);
Label lblDistrict = (Label)row.FindControl("lblDistrict");
ddlDistrict.SelectedIndex = Convert.ToInt32(lblDistrict.Text);
Label lblCity = (Label)row.FindControl("lblCity");
txtCity.Text = lblCity.Text;
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
BindStates();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
BindDistricts();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Customer customers = new Customer();
user = Session["UserDetails"] as User;
customers.ID = hfCustomerId.Value;
customers.Name = txtCustomerName.Text;
customers.Mobile = txtMobileNumber.Text;
customers.Phone = txtPhone.Text;
customers.AddressLine1 = txtAddressline1.Text;
customers.AddressLine2 = txtAddressline2.Text;
customers.Country = ddlCountry.SelectedItem.Value;
customers.State = ddlState.SelectedItem.Value;
customers.District = ddlDistrict.SelectedItem.Value;
customers.City = txtCity.Text;
customers.UpdatedBy = user.ID;
if (Page.IsValid)
{
var result = Customers.UpdateCustomer(customers);
if (result == "Success")
lblMessage.Text = "Sucessfully Updated";
else
lblMessage.Text = "Already Exists";
BindCustomer();
refreshControls();
}
setFormstatus(0);
}
}
}
My grid Code-
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:GridView ID="gvCustomer" runat="server" AutoGenerateColumns="False" CellPadding="4"
EnableModelValidation="True" ForeColor="#333333" GridLines="Both"
onrowcommand="gvCustomer_RowCommand" onrowcreated="gvCustomer_RowCreated">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle HorizontalAlign="Left" CssClass="normalText" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AddressLine1">
<ItemTemplate>
<asp:Label ID="lblAddressLine1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AddressLine2">
<ItemTemplate>
<asp:Label ID="lblAddressLine2" runat="server" Text='<%# Bind("AddressLine2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile">
<ItemTemplate>
<asp:Label ID="lblMobile" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lblPhone" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="District">
<ItemTemplate>
<asp:Label ID="lblDistrict" runat="server" Text='<%# Bind("District") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="linkName" runat="server" Text="Edit" CommandName="displayCustomer" CommandArgument='<%# Eval("ID")%>' >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
select a particular value of drop down from
ddlCountry.SelectedIndex=ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text));
you have find the dropdown, fill it first with your state lists then use
like
ddlState.Items.FindbyText(lblState.text).Selected=true;
you can try like this
if (e.commandname == "displayCustomer") {
GridViewRow gv = (GridViewRow)((Control)e.CommandSource).NamingContainer;
label lblCountry = gv.findControl("lblCountry");
label lblState = gv.findcontrol("lblState");
label lblDistrict = gv.findcontrol("lblDistrict");
//call function to fill your country
ddlCountry.items.finbytext(lblCountry.text).selected = true;
//call function to fill states based on ddlcountry selected item
ddlState.items.finbytext(lblState.text).selected = true;
//call function to fill district based on ddlStateselected item
ddlDistrict.items.finbytext(lblDistrict.text).selected = true;
}
Actually you don't need to perform all this code.
Label lblCountry = (Label)row.FindControl("lblCountry");
ddlCountry.SelectedIndex = Convert.ToInt32(lblCountry.Text);
Label lblState = (Label)row.FindControl("lblState");
ddlState.SelectedIndex = Convert.ToInt32(lblState.Text);
Label lblDistrict = (Label)row.FindControl("lblDistrict");
ddlDistrict.SelectedIndex = Convert.ToInt32(lblDistrict.Text);
One better way is :
<asp:LinkButton ID="linkName" runat="server" Text="Edit" CommandName="displayCustomer" CommandArgument='<%# Eval("ID")%>' ></asp:LinkButton>
public void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Here "i" is the id(CommandArgument='<%# Eval("ID")%>') of the record
//coming from the link button.
int i = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit1")
{
// Execute your Database query with where condition for "i"
// and fetch the value in data reader. The Query will be like
// Select * from Table_Name where ID = i
// This will get you the particular record for that ID only
while (dr.Read())
{
DrpCountry.SelectedItem.Value = dr["CountryID"].ToString();
DrpState.SelectedItem.Value = dr["StateID"].ToString();
DrpDistrict.SelectedItem.Value = dr["DistrictID"].ToString();
}
}
}
UPDATE:
The problem is, when you select the value in your Country DropDown, it is already filled, while your State and City DropDowns are NOT filled that is why they are NOT working,
protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "displayCustomer")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
hfCustomerId.Value = Convert.ToString(e.CommandArgument);
Label lblCName = (Label)row.FindControl("lblCustomerName");
txtCustomerName.Text = lblCName.Text;
Label lblAdd1 = (Label)row.FindControl("lblAddressLine1");
txtAddressline1.Text = lblAdd1.Text;
Label lblAdd2 = (Label)row.FindControl("lblAddressLine2");
txtAddressline2.Text = lblAdd2.Text;
Label lblPhone = (Label)row.FindControl("lblPhone");
txtPhone.Text = lblPhone.Text;
Label lblMobile = (Label)row.FindControl("lblMobile");
txtMobileNumber.Text = lblMobile.Text;
Label lblCountry = (Label)row.FindControl("lblCountry");
// -------------------------- changed code --------------------------
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text))
// at this point country should be filled and selected, so we can bind and select appropriate state
BindStates();
Label lblState = (Label)row.FindControl("lblState");
ddlSate.SelectedIndex = ddlSate.Items.IndexOf(ddlSate.Items.FindByText(lblState.Text))
// at this point states should be filled and selected, so we can bind and select appropriate District
BindDistricts();
Label lblDistrict = (Label)row.FindControl("lblDistrict");
ddlDistrict.SelectedIndex = ddlDistrict.Items.IndexOf(ddlDistrict.Items.FindByText(lblDistrict.Text))
//---------------------------------------------------------------------
Label lblCity = (Label)row.FindControl("lblCity");
txtCity.Text = lblCity.Text;
}
}
As you have mentioned in you comments that Country column in GridView is actually Country Name NOT Country ID. While you are converting this lblCountry.Text into int32 and trying set the index. This should give the error I suppose.
The approach you have currently adopted does NOT seem to right, a better approach may be is to save the ID of the record in the Grid in some HiddenField for example, and on RowCommand, pick the ID from HiddenField, get the data from Database and then load in your input boxes.
Anyway for a workaround, save the CountryID along with your Country Name in a HiddenField,
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
<asp:HiddenField ID="hfCountryID" runat="server" Value='<%# Bind("CountryID") %>'></asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>
Then you can set the DropDown using this CountryID
var hfCountryID = row.FindControl("hfCountryID") as HiddenField;
ddlCountry.SelectedValue = Convert.ToInt32(hfCountryID.Text);
Another workaround can be to find the Item using Country Name and select it,
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText(lblCountry.Text));
all you need is to create a function that get the ID of the country or state or whatever
then you can do :
ddlCounty.SelectedValue=CountyID.ToString();
Try this,
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf
(ddlCountry.Items.FindByText(lblCountry.Text);
I've a ASP.NET GridView with the following data:
Rows will be disable OnRowDataBound based on the value on column3.
GridView :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField HeaderText="Column1">
<ItemTemplate>
<asp:HyperLink ID="hyperlink" runat="server" Text='<% #Eval("Dosage") %>' NavigateUrl='<% #Eval("Dosage") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column2">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<% #Eval("Drug") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column3">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<% #Eval("Patient") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column4">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<% #Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
RowDataBound :
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label a = e.Row.FindControl("Label3") as Label;
if (a.Text == "Sam")
{
e.Row.Enabled = false;
e.Row.Cells[0].Enabled = true;
}
}
}
however, I want column1 always enable, hyperlink in column1 should always clickable.
I've tried get the cells and enabled it, but it is not working.
kindly advise what is the workaround for the issue above.
You can do this by enable/disable particular cell.
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label a = e.Row.FindControl("Label3") as Label;
if (a.Text == "Sam")
{
e.Row.Cells[0].Enabled = true;
e.Row.Cells[1].Enabled = false;
e.Row.Cells[2].Enabled = false;
e.Row.Cells[3].Enabled = false;
}
}
}
I have GridView:
<asp:GridView ID="MyGridView" runat="server" ShowFooter="true"
AutoGenerateColumns="False" Visible="True">
<Columns>
<asp:BoundField DataField="id" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="fullName" />
<asp:TemplateField HeaderText="situation>">
<ItemTemplate>
<asp:DropDownList ID="dl_situation" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<asp:TextBox ID="tbDate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now I want to fill this Grid with data from database, I have one method that returns datatable with all my data
when I fill mygrid:
MyGridView.DataSource = dataTable;
MyGridView.Databind();
in this case all TextBoxes and DropDownList are null.
In the code below I'm trying to create a function that receives DataTable from database and populates gridview with data. How do I make a foreach statement for dataTable.Rows that will assign text values to TextBox elements and selectedIndex value to DropDownList?
protected bool FillGridWithData(DataTable dataTable)
{bool result;
try
{
foreach (GridViewRow row in MyGridView1.Rows)
{
if (row.RowType != DataControlRowType.DataRow) break;
var ddl = (DropDownList)row.FindControl("dl_situation");
if (ddl != null)
{
ddl.DataSource = PublicStatic.Situation;
ddl.DataTextField = PublicStatic.Name;
ddl.DataValueField = PublicStatic.Code;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddl.SelectedIndex = //data from datatable;
}
var tb1 = (TextBox)row.FindControl("tbNr");
if (tb1 != null)
tb1.Text =//data from datatable;
var tb2 = (TextBox)row.FindControl("tbDate");
if (tb2 != null)
tb2.Text = //data from datatable;
}
result = true;
}
catch (Exception exception)
{
result = false;
}
return result;
}
The DataField attribute in the bound field must equal to the column name in the datatable.
For binding textboxes in the template field you can use the Eval or Bind Method.
Example:
<asp:TemplateField HeaderText="procesVerbal">
<ItemTemplate>
<asp:TextBox ID="tbNr" Text='<%# Eval("ColumnName") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and for binding the dropdown in the gridview, you can use a separate sql datasource. and specify dropdownlist DataSourceID,DataTextField and DataValueField property.
Dropdownlist Example:
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1" DataTextField="ProductName" DataValueField="ProductID" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductName], [ProductID] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
and if you want to bind the datasource from code behind then you can use RowDataBound event of gridview
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t = (TextBox)e.Row.FindControl("ControlID");
t.Text = "Some Text";
}
}