I am really bad when it comes to playing with data inside a gridview. Here i have a simple gridview that contains a dropdownlist that gets its data from the database table Products.
what i want is on dropdownlist OnSelectedIndexChanged, the price label should read the price of the selected product in dropdownlist. the issue is when i select a product in dropdownlist the prices doesn't show. label remains empty.
ASP.NET
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="true" PageSize="5" OnRowDataBound="Gridview1_RowDataBound">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="#">
<HeaderStyle CssClass="header" Width="60px"></HeaderStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle CssClass="header" />
<ItemStyle Width="170px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="QTY">
<ItemTemplate>
<asp:TextBox ID="qty_txtbox" runat="server" style="text-align:center;" OnTextChanged="TextBox2_TextChanged"></asp:TextBox>
</ItemTemplate>
<ControlStyle Width="50px" CssClass="txt" />
<HeaderStyle CssClass="header" />
<ItemStyle Width="50px" CssClass="txt" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Price (AED)">
<ItemTemplate>
<asp:Label ID="amount_lbl" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="header" />
<ItemStyle Width="130px" CssClass="txt" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton runat="server" ID="trash" Style="height: 20px;" ImageUrl="~/IMG/garbage.png" />
</ItemTemplate>
<ControlStyle Height="20px" Width="20px"></ControlStyle>
<FooterStyle HorizontalAlign="center" />
<HeaderStyle Height="30px" Width="30px" CssClass="header"></HeaderStyle>
<FooterTemplate>
<asp:ImageButton runat="server" ID="addnew" ImageUrl="~/IMG/add.png" Style="height: 20px;" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="header" />
<PagerStyle CssClass="pagerr" />
<RowStyle CssClass="rows" />
</asp:GridView>
Here is what i tried
private DataSet GetData()
{
SqlCommand cmd = new SqlCommand("SELECT ProductName, PartNumber, price FROM Products");
using (SqlConnection con = new SqlConnection(cDate.CS))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddproducts = (e.Row.FindControl("dropdown1") as DropDownList);
ddproducts.DataSource = GetData();
ddproducts.DataTextField = "ProductName";
ddproducts.DataValueField = "ProductName";
ddproducts.DataBind();
//Add Default Item in the DropDownList
ddproducts.Items.Insert(0, new ListItem("<----Please select---->"));
}
}
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
string dvalue = Gridview1.SelectedRow.Cells[1].Text;
string price = Gridview1.SelectedRow.Cells[3].Text;
using (SqlConnection con = new SqlConnection(cDate.CS))
{
con.Open();
SqlCommand myCommand = new SqlCommand("select price from products where ProductName = #name");
myCommand.Parameters.AddWithValue("#name", dvalue);
myCommand.Connection = con;
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
while (myReader.Read())
{
price = (myReader["price"].ToString());
}
}
}
}
Error
Object reference not set to an instance of an object. for this line string dvalue = Gridview1.SelectedRow.Cells[1].Text;
As the other answer stated, the issue main issues is you are not updating the result in that particular label. But that only solves your issues, you have do something more:
Identify the DataRow in which the control belongs to..
Get the label that you wanted to access.
Perform the operations
Assign the value back to the label.
The whole process can be implemented by using the following code, please take a look and let me know if you need any clarifications:
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlProduct = (DropDownList)sender;
DataGridItem row = (DataGridItem) ddlProduct.NamingContainer;
Label lblPrice = (Label)row.FindControl("amount_lbl");
// Get current label Text
string price = lblPrice.Text;
// Perform your operations here
// Assign the price value back to the label
lblPrice.Text = price;
}
It seems that you didn't set the price back to the grid!
Update: as mentioned by 'un-lucky', to get appropriate grid row we have use the dropdown which fires the event and get associated DataRow in its parents:
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
var row = (sender as DropDownList).NamingContainer as GridViewRow; //instead of Gridview1.SelectedRow;
string dvalue = row.Cells[1].Text; //or row.FindControl(id);
//string price = row.Cells[3].Text;
string price = "1400"; //get from database
row.Cells[3].Text = price; //or row.FindControl(id);
//Gridview1.new
}
Related
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)
I got this simple gridview
<asp:GridView ID="GridViewFoundations" runat="server" AutoGenerateColumns="False"
Width="100%" AllowPaging="True" AllowSorting="True" PageSize="15"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridViewFoundations_PageIndexChanging">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate><asp:Label ID="lb_id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "nodeId") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Foundation Name">
<ItemTemplate><asp:Label ID="lb_foundationName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "text") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastUpdate">
<ItemTemplate><asp:Label ID="lb_lastUpdate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "updateDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expire Date">
<ItemTemplate><asp:Label ID="lb_expireDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "expireDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle 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" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Then I bind if on the page load event , like this
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void BindData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And i have the following filter (for example by text)
protected void btn_filtro_Click(object sender, EventArgs e)
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
My problem is I can't change the index of the page and keep my filters on..
I have already tried
GridViewFoundations.PageIndex = e.NewPageIndex
followed by
gridviewFoundations.Databind() or BindData()
but in the 1st case the gridview desapears and in the second it clears all the filters (obviously) .
So Can anyone help me changing the page of the grid with filters?
In first case(GridViewFoundations.PageIndex = e.NewPageIndex followed by gridviewFoundations.Databind() ) data disappears as you are not providing any datasource to rebing your grid after postback.
In second case(BindData()) you are binding grid without any filters, hence your filter is lost.
what you can do is create a new function
protected void BindFilteredData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
else
BindFilteredData();
}
This will call BindData when your page loads first time and rest of the times it will call filtered data function.
I have drop down box that does not keep the selected value so i had to add this line of code:
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
But adding this line of code is causing me another problem. I have built the dropdown in a Gridview and the Gridview has an Edit link, once you click the edit then you should see the drop down box, but the issue now is when i click the Edit link and nothing has been selected in the dropdown then i get an error. It only works when something was already selected. Here is my code:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
int current_quest_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
DropDownList ddl_Answer = (DropDownList)e.Row.FindControl("ddl_Answer");
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from MainTable D, SecondryTable Q where Q.ANS_OPT = D.ID and QUEST_SK= '" + current_quest_sk + "' ");
cmd1.Connection = con2;
con2.Open();
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
con2.Close();
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
}
here is the markup for the dropdown
<asp:GridView ID="GridView1" runat="server" Width="870px" OnRowDataBound="RowDataBound"
AutoGenerateColumns="False" Font-Names="Arial" Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
HeaderStyle-BackColor="green" AllowPaging="True" ShowFooter="True" OnPageIndexChanging="OnPaging"
OnRowEditing="EditGridView1" OnRowUpdating="UpdateGridView1" OnRowCancelingEdit="CancelEdit"
CellPadding="4" BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px"
DataKeyNames="QUEST_SK">
<AlternatingRowStyle BackColor="#C2D69B" />
<Columns>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" >
<ItemStyle Font-Size="Smaller" ForeColor="#FF3300" />
</asp:CommandField>
</Columns>
Hi I am Presently running an ASP.NET application
Now problem is with the Next button in the app, whenever someone clicks it, it returns the data of date range SYSDATE + 18 to SYDATE + 36 . But the way it should work is .. it should take the first date value from the GridView Date Cell and Returns the data for GridViewFirstCellDate+18 to GridViewFirstCellDate+36. My Gridview code is al follows. Eg the date in Image is Tuesday,November 19,2013 , so clicking Next button should retrun from 7/12/2013 and 25/12/2013 's data (DD/MM/YYYY)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" EnableModelValidation="True" GridLines="Horizontal"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText = "Date">
<ItemTemplate>
<asp:Label ID="Date" Runat="Server"
Text='<%# Eval("DUTY_DATE", "{0:dddd,MMMM dd,yyyy}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Role">
<ItemTemplate>
<asp:Label ID="Role" Runat="Server"
Text='<%# Eval("DUTY_DESC") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("FULLNAME") %>' NavigateUrl='<%# Eval("ROW_PASS", "/sites/HQDO/Pages/OfficerDetails.aspx?_ID={0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("MOBILE_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("OFFICE_TEL") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:GridView>
and the CodeBehind for next button is below
protected void Button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "SELECT CONTACTS.ROWID as ROW_PASS,DUTY_ROTA.DUTY_DATE AS DUTY_DATE,DUTY_ROTA.DUTY_TYPE AS DUTY_TYPE,DUTY_ROTA.DUTY_OFFICER AS DUTY_OFFICER,DUTY_TYPES.DESCRIPTION AS DUTY_DESC,CONTACTS.SNAME AS FULLNAME,CONTACTS.MOBILE AS MOBILE_NO,CONTACTS.OFFICETEL AS OFFICE_TEL FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE+18 and SYSDATE+36 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
}
I tried to catch the value in below way
LabelDate.Text = GridView1.Rows[0].Cells[0].Text;
And then convert it to Date and use it in my SQL. But the LabelDate.Text is unable to store the data not sure why.
Can you buddies please help How could I Capture GridView First Row First Cells data and Add 18 days to it...also I want to use it in my SQL.
You need to add a handler for GridView.RowDataBound
Here's a quick example:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LabelDate.Text = e.Row.Cells[0].Text;
}
Try :
LabelDate.Text = Convert.ToDateTime(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
LabelDate.Text = DateTime.Parse(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("fr-FR");
Label1.Text = DateTime.ParseExact(GridView1.Rows[0].Cells[3].Text, "g", provider).AddDays(18).ToShortDateString();
I have a grid view and when i click on the radiobutton approve it should update the recommend tag value to 1 based on the employeeID.However I am getting an error saying that object is not set to an instance of an object..My columns are also being added to the left..instead of right..Below is the code I have tried.
C# code
public void GridViewBind()
{
dadapter = new SqlDataAdapter("SELECT M_Emp_Personal.EmpName, M_Division.DivShort, M_Designation.DesigShort, T_TADA_tempform.BasicSalary, T_TADA_tempform.GPFNo, T_TADA_tempform.Gradepay,T_TADA_tempform.move_date, T_TADA_tempform.purpose, M_City.CityDesc, T_TADA_tempform.estt_visited, T_TADA_tempform.duration_stay, M_mode.mode_type, T_TADA_tempform.duration_unit, T_TADA_tempform.place, T_TADA_tempform.authority, T_TADA_tempform.exp_debited, T_TADA_tempform.reason FROM T_TADA_tempform INNER JOIN M_Emp_Personal ON T_TADA_tempform.EmpID = M_Emp_Personal.EmpID INNER JOIN M_Division ON T_TADA_tempform.DivisionID = M_Division.DivisionID INNER JOIN M_Designation ON M_Emp_Personal.DesigID = M_Designation.DesigID INNER JOIN M_City ON T_TADA_tempform.CityID = M_City.CityID INNER JOIN M_mode ON T_TADA_tempform.mode_ID = M_mode.mode_ID where M_Emp_Personal.EmpID=" + ddlname.SelectedValue + "", conn);
dset = new DataSet();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
}
protected void submit_info(object sender, EventArgs e)
{
GridViewRow grow = (GridViewRow)(sender as Control).Parent.Parent;
RadioButton rbpApprove = (RadioButton)grow.FindControl("rbtnapprove");
RadioButton rbpReject = (RadioButton)grow.FindControl("rbtnreject");
if (rbpApprove.Checked == true)
{
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE T_TADA_tempform SET Recommened_tag =1 where EmpID=#EmpID", conn);
cmd.Parameters.AddWithValue("#EmpID", ddlname.SelectedValue);
conn.Close();
}
this is my ASP.NET code
<asp:GridView ID="GridView1" runat="server" CssClass="vutblrow" TabIndex="6"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%"
PagerStyle-Mode="NumericPages" >
<PagerStyle CssClass="pgr" Height="25px" BorderStyle="Solid" />
<Columns>
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:RadioButton runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:RadioButton runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField><asp:TemplateField HeaderText="Submit">
<ItemTemplate>
<asp:Button CssClass="btnAction" Text="Sumbit" runat="server" OnClick="submit_info" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="vutblhdr" />
</asp:GridView>
You will see that error when you're trying to use an object that hasn't been initialised correctly.
Likely candidates are:
RadioButton rbpApprove = (RadioButton)grow.FindControl("rbtnapprove");
RadioButton rbpReject = (RadioButton)grow.FindControl("rbtnreject");
If the rbpApprove Control isn't found then this line here:
if (rbpApprove.Checked == true)
Will give you the error you are getting.
However only seeing a subset of your code it could be elsewhere.
I think you are missing the Ids of the radionbuttons, try this
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:RadioButton ID="rbtnapprove" runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reject">
<ItemTemplate>
<asp:RadioButton ID="rbtnreject" runat="server" GroupName="status" />
</ItemTemplate>
</asp:TemplateField>
And call Execute
if (rbpApprove.Checked == true)
{
conn.Open();
SqlCommand cmd = new SqlCommand("UPDATE T_TADA_tempform SET Recommened_tag =1 where EmpID=#EmpID", conn);
cmd.Parameters.AddWithValue("#EmpID", ddlname.SelectedValue);
cmd.ExecuteNonQuery();
conn.Close();
}