Get row id on button click - c#

I need to get a row id from database with the button click.
This is my c# code:
protected void ddlBC_SelectedIndexChanged(object sender, EventArgs e)
{
LogicTableAdapters.getLvLKarTableAdapter getKar = new LogicTableAdapters.getLvLKarTableAdapter();
DataTable dtKar = getKar.getLvLKar(ddlBC.SelectedValue);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("CharName", typeof(string)),
new DataColumn("LevelID", typeof(int))
});
foreach (DataRow dr in dtKar.Rows)
{
dt.Rows.Add(dr["CharName"].ToString(), dr["LevelID"].ToString());
}
gvKar.DataSource = dt;
gvKar.DataBind();
}
protected void btnButton_Click(object sender, EventArgs e)
{
}
This is dynamically GridView that gets populated by the procedure when item in ddl is selected:
<asp:GridView ID="gvKar" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="LevelID" OnRowDataBound="gvKarakteristike_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Kar">
<ItemTemplate>
<asp:Label ID="Kar" runat="server" Width="150px" Height="30px" Font-Names="Georgia" MyCustomAttr="foo" margin-Left="100px" Text='<%# Bind("CharName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnButton" runat="server" Text="Show" autopostback="True"/>
When the button is clicked in form of alert row id from every row must be shown from database.
Can anyone help me please ?

I use code like this to assign a click handler to the row:
Protected Sub Grid_RowDataBound(sender As Object, e As GridViewRowEventArgs)
'apply click attribute to select a row
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(sender, "Select$" & e.Row.RowIndex)
End If
End Sub
Then this to get the relevant data from the datakeys collection
Protected Sub Grid_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Select" Then
Dim LevelID As String = GridResults.DataKeys(e.CommandArgument).Item("LevelID")
' Do something with ID here
End If
End Sub

Related

ASP.NET control in GridView not found to exist in code behind

I have a DropDownList that I would like to populate with column values from a DataBase. However, when I try to bind the DropDownList in code behind, the IDE keeps telling me:
"The name 'EqpCatDDL' does not exist in the current context"
I am not sure what is going on since I referred to the control by its ID. The following is the code:
aspx:
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false"
>
<Columns>
<asp:BoundField DataField="S/N" HeaderText="S/N" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="EqpCatDDL" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="DescripDDL" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
c#:
public void Populate1()
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection);
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
EqpCatDDL.DataSource = ddlValues;
EqpCatDDL.DataValueField = "EqpCateID";
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
Populate1();
}
The IDE can't find the EqpCatDDL control.
I am using the following: Visual Studio 2010, Microsoft SQL Server Management Studio 2008
I am working with a Visual Studio website
Use this code to bound data to dropdown without using RowDataBound.
Create a function that'll bind the Data to dropdown as follow and call it in Page_Load event
Public void fill_gridView_dropDown()
{
// your connection and query to retrieve dropdown data will go here
// this loop will go through all row in GridView
foreach(GridViewRow row in your_gridView_Name.Rows) {
DropDownList dropDown = (DropDownList)row.FindControl("dropDownList_id");
dropDown.DataSource = dataSource;
dropDown.DataValueField = "ValueField";
dropDown.DataTextField = "TextField";
dropDown.DataBind();
}
}
Please note that you have to bind GridView first, and then you have to bind your dropdown
your dropdown is in gridview so you can try with this code
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("EqpCatDDL'");
SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
EqpCatDDL.DataSource = ds;
EqpCatDDL.DataValueField = "EqpCateID";
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataBind();
}
}
You can't directly populate GridView's dropdownlist like this. You need to set datasource of GridView first i.e.
GridView1.DataSource = DataSource
And if you would like to access dropdownlist of this gridview, you can use RowDataBound event handler of GridView i.e.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking whether the Row is Data Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding the Dropdown control.
Control ctrl = e.Row.FindControl("EqpCatDDL");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
List lst = new List();
dd.DataSource = lst;
dd.DataBind();
}
}
}

paging in gridview from dataset

i have a datset that i save into viewstate and i want to paging on that dataset.
Code for bind gridview
DataSet _ds = _fOrderInvoice.ExecuteDataSet();
ViewState["FIOrders"] = _ds.Tables[0];
grdInvoiced.DataSource = _ds; // bind the gridview
Now i want paging on the gridview. So how can i do that from the dataset that i have save into my ViewState["FIOrders"]. My gridview is below
<asp:GridView ID="grdInvoiced" runat="server" Width="100%" ViewStateMode="Enabled" DefaultSortColumnName="OrderNo" OnSelectedIndexChanged="GridInvoice_SelectedIndexChanged" AutoGenerateColumns="False" OnSorting="invoice_sorting" OnRowDataBound="grdInvoice_Rowdatabount" ShowFooter="true" PageSize="20" AllowPaging="True" AllowSorting="True" DataKeyNames="OrderNo" ExcelExportFileName="Export_AccountTerms.xls"
ShowHeaderWhenEmpty="true" OnPageIndexChanging="grdInvoiced_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="View" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="rbtnSelect" GroupName="a" runat="server" />
<asp:Literal ID="ltOrder" runat="server" Text='<%# Eval("OrderNo")%>' Visible="false"></asp:Literal>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" Width="50px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
PageIndexChanging event
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex+1;
if (ViewState["FOrders"] != null)
{
DataTable ds = (DataTable)ViewState["FIOrders"];
grdInvoiced.PageIndex = e.NewPageIndex + 1;
// Collection<FinalizedOrderInvoiceRows> _rows = ViewState["FIOrders"] as Collection<FinalizedOrderInvoiceRows>;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}
Convert Your ViewState into DataSet and Bind it to GridView
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex;
if (ViewState["FOrders"] != null)
{
DataSet ds =(DataSet) ViewState["FIOrders"] ;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}

how to add different control in gridview row

I have a gridview which I populate from the list data. every row in the gridview has a text box. there is one row within the gridview which I want a dropdown control rather then the textbox. I can't figure out how to change the textbox to dropdown control from a row in the grid.
My gridview below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" style="width:100%;" ShowHeader="false"
CellPadding="3" BackColor="White" ForeColor="Black" Font-Bold="false" GridLines="None"
RowStyle-CssClass="GridRow">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemID" runat="server" Text='<%# Eval("GroupItemTypeID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemCode" runat="server" Text='<%# Eval("GroupItemTypeCode") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="310px" >
<ItemTemplate>
<asp:Label ID="lbl_ItemValuesName" runat="server" Text='<%# Eval("ControlName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="RowWid">
<ItemTemplate>
<asp:Label ID="lbl_IsPercentbased" runat="server" Text='<%# Eval("PercentBasedText") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="70px">
<ItemTemplate>
<asp:CheckBox ID="ChkIsPercent" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void GetItemValues()
{
List<Entities.ItemValues> IValues = new List<Entities.ItemValues>();
IValues = BLL.PriceGroupItemValues.GetAllPriceGroupItemValues();
GridView1.DataSource = IValues;
GridView1.DataBind();
}
You can go for this approach in your case :
Put a TextBox and DropDown both in that TemplateField where your TextBox is currently, and set Visible=false in your Dropdown.
Now in your code-behind, you can use the GridView.RowDataBound event to alternatively display the TextBox or the Dropdown whenever and wherever you require. Something like this :
public void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// set Dropdown visible = true/false as per your requirement.
}
else
{
// set Textboxvisible = true/false as per your requirement.
}
}
This event will fire up for ear row in your GridView and based on the condition that is specified, you can manipulate which control you want to show in that particular row. You can find the dropdown control like this :
foreach (GridViewRow row in GridView1.Rows)
{
categoryName = ((DropDownList)row.FindControl("ddlCategoryName"));
}
Hope this helps.
Use a placeholder control instead of a textbox and programmatically add either a textbox or DDL to the Placeholder control in the rowdatabound event based on your criteria
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
DataKeyNames="user_id">
<Columns>
<asp:BoundField DataField="user_id" HeaderText="user_id" ReadOnly="True" InsertVisible="False"
SortExpression="user_id"></asp:BoundField>
<asp:BoundField DataField="user_logon" HeaderText="user_logon" SortExpression="user_logon">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Sample DataSources
'Primary Datasource to bind to the gridview
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 10 user_id, user_logon from your_user_table"></asp:SqlDataSource>
'Secondary datasource to bind to the ddl
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 5 user_id, user_logon from your_user_table"></asp:SqlDataSource>
Code behind, based on the whether the user_id is odd or even I place one or the other control:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If GridView1.DataKeys(e.Row.RowIndex).Value Mod 2 = 0 Then
Dim tb As New TextBox()
tb.Enabled = False
tb.Text = CType(e.Row.DataItem, DataRowView)("user_logon")
ph.Controls.Add(tb)
Else
Dim ddl As New DropDownList()
ddl.DataSourceID = SqlDataSource2.ID
ddl.DataTextField = "user_logon"
ddl.DataValueField = "user_id"
ph.Controls.Add(ddl)
ddl.DataBind()
End If
End If
End Sub
EDIT based on your Comments:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If CType(e.Row.DataItem, DataRowView)("GroupItemTypeID") ="SUBFREQ" Then
Dim ddl As New DropDownList()
ddl.DataSourceID = <substitute your requirements>
ddl.DataTextField = ...
ddl.DataValueField = ...
ph.Controls.Add(ddl)
ddl.DataBind()
Else
Dim tb As New TextBox()
tb.Enabled = ...whatever...
tb.Text = CType(e.Row.DataItem, DataRowView)("GroupItemTypeID")
ph.Controls.Add(tb)
End If
End If
End Sub
Did some work around with the solution Harvey provided and my existing code. Posting my answer here.
In the gridview, created 2 control and visibility of one control(dropdown) to false
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
<asp:DropDownList ID="ddFrequencyBilling" runat="server" CssClass="form-control" Visible="false"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
In the RowDataBound event of the gridview
if (e.Row.RowType == DataControlRowType.DataRow)
{
//foreach( GridViewRow row in GridView1.Rows)
//{
String ItemCode = (e.Row.FindControl("lbl_ItemCode") as Label).Text;
if ( ItemCode == "SUBFREQ")
{
List<Entities.ItemValues> PGItemValues = new List<Entities.ItemValues>();
TextBox TextBoxtemp = ((TextBox)e.Row.FindControl("txtPrice"));
TextBoxtemp.Visible = false;
Label lbel = ((Label)e.Row.FindControl("lbl_IsPercentbased"));
lbel.Visible = false;
CheckBox chk = ((CheckBox)e.Row.FindControl("ChkIsPercent"));
chk.Visible = false;
DropDownList dd1 = ((DropDownList)e.Row.FindControl("ddFrequencyBilling"));
dd1.Visible = true;
PGItemValues = BLL.PriceGroupItemValues.GetItemValueOnCode(ItemCode, 1);
dd1.DataSource = PGItemValues;
dd1.DataTextField = "IValue";
dd1.DataValueField = "ItemCode";
dd1.DataBind();
}
//}
}
and yes it worked. Thanks alot guys.

Find row of an item template control in gridview

I have a gridview in ASP.NET with a item template which holds a drop down list. I have an event for the drop down list (selected index changed) in which I need to figure out which row, in the gridview, this control resides in. Anyone know how to accomplish this? (I add more rows later, so this is why I need the row I am in.)
<asp:gridview ID="grdTest" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Query Line" />
<asp:TemplateField HeaderText="Table Name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// TODO: Grab the row of the control here!
int row = 0;
DropDownList ddl = (DropDownList)sender; // How?
}
you can do it like this,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList) sender;
GridViewRow row = (GridViewRow) ddl.NamingContainer;
int rowIndex = row.RowIndex;
}
Below code will help you
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gvrow As GridViewRow = CType(sender, DropDownList).NamingContainer
Dim index As Integer = CType(gvrow, GridViewRow).RowIndex
End Sub

Making a column editable in an ASP.net GridView

I have a GridView where one of the columns is for a display order for the fields where they will be shown on the front end of my website. Instead of going into each record in the edit page and having to change the order this way, it would be handier to be able to click a button and have the whole DisplayOrder (int) editable, therefore making life alot easier. How can this be done?
Try this code :
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>Manager1</asp:ListItem>
<asp:ListItem>Manager2</asp:ListItem>
<asp:ListItem>Manager3</asp:ListItem>
<asp:ListItem>Manager4</asp:ListItem>
</asp:ListBox>
<asp:GridView ID="UserAllocationGrid" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Manager" HeaderText="Manager"
SortExpression="managers" />
<asp:TemplateField HeaderText="Allocation Percentage">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text= '<%# Bind("AllocationPercentage") %>' BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
void fillGV()
{
DataTable UserAllocationTable = new DataTable();
UserAllocationTable.Columns.Add("Manager");
UserAllocationTable.Columns.Add("AllocationPercentage");
// go through listbox1 to find selected managers = selectedManagersList
List<string> selectedManagersListDates = new List<string>();
int counterR = 0;
foreach (ListItem strItem in ListBox1.Items)
{
//selectedManagersListDates.Add(strItem.Value);
DataRow drManagerName = UserAllocationTable.NewRow();
UserAllocationTable.Rows.Add(drManagerName);
UserAllocationTable.Rows[counterR]["Manager"] = strItem.Value;
counterR = counterR + 1;
}
// ViewState["UserAllocationTable"] = UserAllocationTable;
UserAllocationGrid.DataSource = UserAllocationTable;
UserAllocationGrid.DataBind();
}
Use this void in any event I did it in abutton click
protected void Button1_Click(object sender, EventArgs e)
{
fillGV();
}
You can try this using ShowDeleteButton="true" in asp commandfield you can make gridview edidable :-
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
may be help you
You can try below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton = "true">
<Columns>
<asp:BoundField DataField="prodId" HeaderText="Product Id" SortExpression="prodId" ReadOnly = "true" />
<asp:BoundField DataField="prodQuantity" HeaderText="Quantity"
SortExpression="prodQuantity" ReadOnly = "true" />
</Columns>
</asp:GridView>
At Gridview level set AutoGenerateEditButton = "true". This will enable user to edit row.
At Data Field level use ReadOnly = "true" to prevent specific field(in row) from being edited.
Hope this helps.
You can try this, it will give text boxes in column
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>'></asp:Label>
<asp:TextBox ID="Description" runat="server"
Text='<%# Eval("Description") %>' Width="175px"
visible="false"></asp:TextBox>
</ItemTemplate>
This link had the answer I was looking for. If you have a custom data source, must handle Edit each edit event raised by GridView. In my case:
Protected Sub gMaterias_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles gMaterias.RowCancelingEdit
gMaterias.EditIndex = -1
BindData()
End Sub
Protected Sub gMaterias_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles gMaterias.RowEditing
gMaterias.EditIndex = e.NewEditIndex
BindData()
End Sub
Protected Sub gMaterias_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles gMaterias.RowUpdating
lError.Visible = False
lError.Text = ""
Dim idMateria As Integer = e.Keys(0)
Dim row As GridViewRow = gMaterias.Rows(e.RowIndex)
Dim tbl As DataTable = Session("Materias")
tbl.Rows(row.DataItemIndex)("universidad") = CType(gMaterias.Rows(e.RowIndex).Cells(5).Controls(0), TextBox).Text
Dim calf = CType(gMaterias.Rows(e.RowIndex).Cells(6).Controls(0), TextBox).Text
If IsNumeric(calf) Then
tbl.Rows(row.DataItemIndex)("calificacion") = calf
Else
lError.Visible = True
lError.Text = "La calificación no es válida"
End If
gMaterias.EditIndex = -1
BindData()
End Sub

Categories

Resources