Get column value an GridView - c#

I have an GridView with button "Delete".
I need get value to column or cell of index[3].
But with GridView1.SelectedRow.Cells[3].Text; it return null.
Someone help me? I do not want use javascript.
My aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" GridLines="None"
CssClass="table table-bordered table-striped">
<Columns>
<asp:BoundField DataField="DisplayName" HeaderText="Display Name" />
<asp:BoundField DataField="UserName" HeaderText="User Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_OnClick" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My .cs:
protected void btnDelete_OnClick(object sender, EventArgs e)
{
using (objConexao = new SqlConnection(strStringConexao))
{
SqlConnection oConn = new SqlConnection();
SqlCommand oCommand = new SqlCommand();
string strConn = ConfigurationManager.ConnectionStrings["XXX"].ConnectionString;
oConn.ConnectionString = strConn;
oCommand.Connection = oConn;
oCommand.CommandText = "proc_Delete";
oCommand.CommandType = CommandType.StoredProcedure;
SqlParameter myParam = oCommand.Parameters.Add("#UserRequestor", SqlDbType.NVarChar);
myParam.Value = User;
SqlParameter myParam2 = oCommand.Parameters.Add("#UserName", SqlDbType.NVarChar);
myParam2.Value = GridView1.Columns[3].ToString();
oConn.Open();
oCommand.ExecuteNonQuery();
oConn.Close();
}
}

Try this:
protected void btnDelete_OnClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer
string desiredText = row.Cells[3].Text;
using (objConexao = new SqlConnection(strStringConexao))
{
// ...
myParam2.Value = desiredText;
// ...
}
}
NamingContainer will get you the row of the Button that was clicked
I don't think that the SelectedRow property worked because clicking a button does not constitute selecting a row. That is done with CommandName="Select" on a button, or with AutoGenerateSelectButton="true" on your GridView. This question provides an explanation.

It's been a while, but I know you can use datakeynames for this.
In the markup add a key for whatever value you want to access
<asp:GridView ID="GridView1" DataKeyNames="Email" runat="server" AutoGenerateColumns="false" GridLines="None"
CssClass="table table-bordered table-striped">
Then you should be able to get the value with the row index as such.
GridView1.DataKeys[3].Value.ToString()
It's been a while, so you might have to play with this.
Here's an article with more information, and how to have more than one datakey

Related

RowIndex of row of which dropdown was selected

Reference image of the GV
So OnSelectedIndexChanged of the dropdown in 7th cell I want to enable or disable the Remarks column (last column) of that row
Gridview.aspx
<asp:GridView ID="grdassetslist" runat="server" AutoGenerateColumns="false" BackColor="Transparent" BorderColor="Black" BorderStyle="Dashed" BorderWidth="1px" CellPadding="4"
DataKeyNames="ID" AutoGenerateSelectButton="true" CellSpacing="2" OnRowDataBound="grdassetslist_RowDataBound" HeaderStyle-ForeColor="Black" HeaderStyle-BackColor="#66ccff"
OnSelectedIndexChanged="grdassetslist_SelectedIndexChanged" HorizontalAlign="Center" HeaderStyle-CssClass="grd" RowStyle-CssClass="grd" AllowPaging="true" PageSize="15"
OnPageIndexChanged="grdassetslist_PageIndexChanged" OnPageIndexChanging="grdassetslist_PageIndexChanging">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:HiddenField ID="hdnAstID" runat="server" Visible="false" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Asset Category" ReadOnly="true" />
<asp:BoundField DataField="SAPAssetCode" HeaderText="SAP Asset Code" ReadOnly="true" />
<asp:BoundField DataField="ITAssetCode" HeaderText="IT Asset Code" ReadOnly="true" />
<asp:BoundField DataField="Make" HeaderText="Make" ReadOnly="true" />
<asp:BoundField DataField="ModelNo" HeaderText="ModelNo" ReadOnly="true" />
<asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" ReadOnly="true" />
<asp:BoundField DataField="AssetStatus" HeaderText="Current Status" ReadOnly="true" />
<asp:TemplateField HeaderText="Change Status To">
<ItemTemplate>
<asp:DropDownList ID="ddl_each_asset_status" runat="server" Width="100px" Height="25px" CssClass="dd" AutoPostBack="true" OnSelectedIndexChanged="ddl_each_asset_status_SelectedIndexChanged1" CausesValidation="false" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CurrentUser" HeaderText="CurrentUser" ReadOnly="true" />
<asp:TemplateField HeaderText="Remarks for Status change">
<ItemTemplate>
<asp:TextBox ID="txtrmrks" runat="server" placeholder="Remarks (if any)" ReadOnly="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Assests" HeaderText="" ReadOnly="true" />--%>
</Columns>
<HeaderStyle HorizontalAlign="Center"/>
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
GridLoad.apx.cs
con.Open();
DropDownList DropDownList1 = (e.Row.FindControl("ddl_each_asset_status") as DropDownList);
SqlCommand cmd = new SqlCommand("select ID,Code[Title] from tbl_assetstatus (nolock) where ID<>2 and IsActive=1 order by ID", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Title";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Status", "0"));
SelectedIndexChanged event:
protected void ddl_each_asset_status_SelectedIndexChanged1(object sender, EventArgs e)
{
//Code to Enable or Disable the remarks column of that row of which the dropdown was changed?
}
Please add the code for SelectedIndexChanged for this.
Thanks in Advance
If you using GridView, then I doubt this is a .net core application?
And really, to help us out here - try posting at LEAST SOME of your gridviewe markup, as then we not trying to play a game of darts in a room with the lights out.
Assuming a GV like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table table=table-hover" Width="800px"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="First name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField="City"
DataValueField="City"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="lbl1" runat="server" Height="179px" Width="450px" TextMode="MultiLine">
</asp:Label>
</div>
Code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT City FROM City ORDER BY City";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstCity.Load(cmdSQL.ExecuteReader());
cmdSQL.CommandText =
"SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
Ok, and now the code for the combo box (dropdown list). We assume auto-post back, so the code is thus this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string cr = System.Environment.NewLine;
string sResult =
$"Row index = {gRow.RowIndex} \n DataBase PK = {PK} <br/>" +
$" Hotel = {gRow.Cells[3].Text} <br/>" +
$"Combo Box selection = {cboCity.Text}";
lbl1.Text = sResult;
}
and thus we see/get this:
Edit2:
I should also note the following additonal information:
Of course I have to fill/load the drop down.. and that is done in row data bound event. Eg this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
cboCity.Items.Insert(0,new ListItem("Select", ""));
if (gData["City"] != DBNull.Value)
{
cboCity.Text = gData["City"].ToString();
}
}
}
Also, note how I don't care (or bother) with the GV selected index changed event. I really don't need it. I as noted, simple set autopost-back = true.
Last but not least?
you of course cannot build ANY working webforms page if you attemptto load up data in on-load but FORGET to check isPostback.
Since any button click, any post-back, or anything causing a post-back will of course trigger the page load event again, and BEFORE any of your other events. Thus, you need to ALWAYS ensure that you only load up the information one time on page load, since if you re-load the gv, or even a dropdown, then you tend to lose that choice by the user being made.
thus, that all imporant !IsPostBack stub is required for most pages.
Eg this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
next up:
Since the dropdown list has the one grid row, then you are free to get data, hide data, enable or do whatever you please.
Just keep in mind that
For built in "databound" columns, you use the cells[] colleciton.
For any templated control, then you use gRow.FindControl("control name here")
So, since your "goal" in question is to operate on "txtrmrks" then that is a templated column, and thus we have to use findcontrol.
Say, like this:
air code warning!!!
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
TextBox txtrmrks = (TextBox)gRow.FindControl("txtrmrks");
if (cboCity.Text == "Banff")
{
// disable the txtrmrks box
txtrmrks.Enabled = false;
}
}
You also not clear if you are going to working the value returned from the cbo box as "id", or "Title"
I suggest this way, and not to use ".Text" of the cbo, but this:
cboCity.SelectedItem.Value (gets value - ID)
cboCity.SelectedItem.Text (gets Text - Title)
if (cboCity.SelectedItem.Text)

Input string was not in a correct format. Visual Studio 2017

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[rowIndex];
row.Cells[1].Text = "ACCEPTED";
string msg = "ACCEPTED";
Session["c_email"] = row.Cells[4].Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Status values(#email,#c_email,#status)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["c_email"].ToString());
cmd.Parameters.AddWithValue("#email", Session["mechanic"].ToString());
cmd.Parameters.AddWithValue("#status", msg.ToString());
cmd.ExecuteNonQuery();
Label1.Text = "You need to reach the customer within one hour and provide the needful service.";
con.Close();
}
I have been trying to solve this error but couldn't do so. The string is not in correct format, this error is popping. But what could be the solution? I have tried a several ways like "int.Parse", "Int32.TryParse" and also I added e.CommandArgument.ToString()
But all was just of no use. Please help me out with this error.
Thanking you with anticipation.
.aspx code:
<asp:GridView ID="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand"
CssClass="table-bordered table-hover table-responsive table"
BackColor="White" BorderColor="White" CellPadding="3"
DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnpreview" runat="server" Text="Accept" CommandName="Accept" />
<asp:Button ID="btnselect" runat="server" Text="Reject" CommandName="Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Status" />
<asp:BoundField DataField="first_name" HeaderText="First name" SortExpression="first_name" />
<asp:BoundField DataField="last_name" HeaderText="Last name" SortExpression="last_name" />
Change Accept button to-
<asp:Button ID="btnpreview" runat="server" Text="Accept" CommandName="Accept" CommandArgument='<%# Container.DataItemIndex%>' />
Note CommandArgument='<%# Container.DataItemIndex%>' in above line, this will give you index of row.
OR
You can change your code behind to-
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;

Getting data from gridview to textbox in asp.net c# using link button

Here is my aspx.cs page code. Every time when I run the code the only answer I get is: Column name doesn't exist.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="table table-striped table-bordered table-hover" >
<Columns>
<asp:BoundField DataField="TutorialId" HeaderText="Tutorial Id"/>
<asp:BoundField DataField="TutorialTitle" HeaderText="TutorialTitle"/>
<asp:BoundField DataField="CatId" HeaderText="Category Id" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" OnClick="lnk_OnClick"
CommandArgument='<%#Eval("TutorialId") %>'>View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my aspx code. Here I have used click event on the link
button which is getting the ID number:
protected void lnk_OnClick(object sender, EventArgs e)
{
int TutorialId = Convert.ToInt32((sender as LinkButton).CommandArgument);
GetTutorialById();
}
private void GetTutorialById()
{
OnlineSubjects onlinesubject = new OnlineSubjects();
DataTable dTable = onlinesubject.GetTutorialById();
txtTutId.Text = dTable.Rows[0]["TutorialId"].ToString();
txtTitle.Text = dTable.Rows[0]["TutorialTitle"].ToString();
txtAddTutorial.Text = dTable.Rows[0]["TutorialDesc"].ToString();
}
public DataTable GetTutorialById()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter(
"#TutorialId", TutorialId, System.Data.SqlDbType.Int, 100);
DataTable dTable = DataLayer.DataAccess.ExecuteDTByProcedure(
"spTutorialViewById", parameters);
return dTable;
}

Trying to add a second level nested table without sucess

I am trying to learn how to add an additional nested table inside the firstLevelGrid but I am not succeding. Any help would be appreciated.
Particularly I am doing something wrong in managing the OnRowDataBound when I create the second level grid, both in the markup and the code behind.
This is the code I have that generate the grid and the first level. I have not added my attempts for the second level grid just to avoid to mess up the code.
It is not homework, I am not a professional coder and I am a selflearner.
<div>
<asp:GridView ID="zeroLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="Code" OnRowDataBound="OnRowDataBoundZeroLevel">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="firstLevelPanel" runat="server" Style="display: none">
<asp:GridView ID="firstLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<!-- Here is where I add the second level grid copying the entire block "TemplateFiled" of the firstLevelGrid and renaming it secondLevel...-->
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
and my c# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
zeroLevelGrid.DataSource = GetData("select top 10 * from Table_xx");//top10 only for test purposes
zeroLevelGrid.DataBind();
}
}
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["Test1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBoundZeroLevel(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = zeroLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView firstLevelGrid = e.Row.FindControl("firstLevelGrid") as GridView;
firstLevelGrid.DataSource = GetData(string.Format("IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')) SELECT * from [{0}]", code));
firstLevelGrid.DataBind();
}
}
//here is where I add an OnRowDataBound event copying the above one as OnRowDataBoundFirstLevel
//but then I get lost...
}
I would be glad if someone could indicate me how to add an additional level of nested grid inside the firstLevelGrid identical to it. I would be happy to offer a bounty to get this right but unfortunatelly I do not have enough rep yet. Thank you a lot.
Similart to your firstLevelGrid, you have to declare the third level grid inside the firstLevelGrid as a template column
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="secondLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<%--Your columns go here--%>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
Then handle OnRowDataBound event for the firstLevelGrid
OnRowDataBound="firstLevelGrid_OnRowDataBound"
In the RowDataBound event you can get the grid view, data key and bind the child grid
protected void firstLevelGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView firstLevelGrid = e.Row.NamingContainer as GridView;
string code = firstLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView secondLevelGridView = e.Row.FindControl("secondLevelGrid") as GridView;
secondLevelGridView.DataSource = //GetData
secondLevelGridView.DataBind();
}
}

Dynamic parameter passing through hyperlink in a DataGrid in asp.net(C#)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
CellPadding="4">
<Columns>
<asp:BoundField DataField="FileID" HeaderText="FileID" />
<asp:BoundField DataField="FilePath" HeaderText="FilePath" />
<asp:BoundField DataField="UploadedBy" HeaderText="CreatedBy" />
<asp:BoundField DataField="CreatedDate" HeaderText="CreatedDate" />
<asp:HyperLinkField HeaderText="LINK" NavigateUrl="show.aspx" Text="SHOW" />
</Columns>
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (NAME.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
else
{
GridView2.DataSource = rdr;
GridView2.DataBind();
}
rdr.Close();
I want to use the hyperlink in the Gridview to pass the values dynamically according to to the row it is clicked.As I'm new to this I'm not able to do that.Please anybody help me.
Set hyperlink NavigateUrl property like...NavigateUrl='<%# Eval("FileID", "show.aspx?ID={0}" %>'
NavigateUrl='<%# Eval("FileID", "show.aspx?ID={0}") + "&FilePath=" + Eval("FilePath") %>'
add onRowCommand Event in your grid
OnRowCommand="OnRowCommand_GridView1"
Then define link Button with the CommandName and CommandArgument
<asp:LinkButton ID="lnk1" runat="server" Text="DoClick" CommandName="Select" CommandArgument='<%#Eval("FileID") %>'></asp:LinkButton>
and than on code behind
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int MyFileID = e.CommandArgument;
//Now Perfrom here ur desired action
}
Hope this will help you.
Check onRowCommand of GridView
Check the following link:
How to get the current row in GridView Row Command Event?
For information about row command: GridView.RowCommand Event

Categories

Resources