RowIndex of row of which dropdown was selected - c#

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)

Related

Reading values in Gridview on Selection change of a DropDownList

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
}

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();
}
}

Get column value an GridView

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

Issue with getting CheckBox value in GridView

I have a GridView that contains a CheckBox control. Once the users check the rows that they want, they click a button and I have to update the database for each checked row.
I have the code to iterate trough the gridview rows and look at the checkbox value, but its always false, even if its checked. I do get a reference to the checkbox in ignore but it is always false. What am I missing here?
aspx.cs file:
protected void Ignore_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdNotReceived.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ignore = (CheckBox)row.FindControl("chkIgnore");
if (ignore.Checked)
{
// Update Database
}
}
}
}
.aspx page:
<asp:GridView ID="grdNotReceived" runat="server"
Width="600px"
CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
PagerStyle-CssClass="pgr" AutoGenerateColumns="false">
<AlternatingRowStyle CssClass="alt"/>
<Columns>
<asp:BoundField DataField="Store" HeaderText="Store" />
<asp:BoundField DataField="Dept" HeaderText="Dept" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="RefNumber" HeaderText="RefNumber" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Vendor" HeaderText="Vendor" />
<asp:BoundField DataField="Total" HeaderText="Total" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView databind method:
protected void LoadExceptions()
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
If your databinding function ( LoadExceptions() ) is being called somwhere on the page load (like the Load event or class constructor) then it's overriding the changes the user has made in the form.
Don't databind if the page is in post back, you can add an if (!Page.IsPostBack) before calling LoadExceptions() or you can update LoadExceptions() to check it:
protected void LoadExceptions()
{
if (!Page.IsPostBack)
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
}

ASP.Net C# Gridview CheckBox Questiom

I am creating a web app using asp.net and c#. I am using gridview to display a list of staff from the database. I have added a checkbox so that the user can choose the staff they wish to pick. However when I go to check where the user clicked all the checkboxes show up unclicked.
This is my code:
<asp:GridView runat="server" id="gvPickStaff" GridLines="Horizontal" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="idusers" HeaderText="ID " ReadOnly="true" />
<asp:BoundField DataField="first_name" HeaderText="Name " ReadOnly="true" />
<asp:BoundField DataField="job_title" HeaderText="Job Title " ReadOnly="true" />
<asp:BoundField DataField="code_quality" HeaderText="Code Quality" ReadOnly="true" />
<asp:BoundField DataField="time_bonus" HeaderText="Time Bonus" ReadOnly="true" />
<asp:BoundField DataField="analysis_of_requirements" HeaderText="Analysis Of Requierements" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbxSelect" runat="server" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The Code Behind where I found the problem:
protected void btnAddStaff_OnClick(object sender, EventArgs e)
{
foreach(GridViewRow rowitem in gvPickStaff.Rows)
{
chk = (CheckBox)(rowitem.Cells[0].FindControl("cbxSelect"));
if(chk.Checked)
{
int staffid = Convert.ToInt32(gvPickStaff.DataKeys[rowitem.RowIndex]["idusers"]);
staffChosen.Add(staffid);
}
}
}
I fill the gridview like this:
protected void fillStaffChoiceList()
{
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idusers, first_name, job_title, code_quality, time_bonus,analysis_of_requirements FROM `test`.`users` WHERE security_level > 1";
//SELECT idusers, first_name, last_name, job_title, code_quality, time_bonus,analysis_of_requirements FROM `test`.`users` WHERE security_level > 1;
connection.Open();
reader = command.ExecuteReader();
gvPickStaff.DataSource = reader;
gvPickStaff.DataBind();
connection.Close();
}
Can anyone perhaps see where I am going wrong?
I think problem is in page load
try this
public void Page_Load(object sender,EventArgs e)
{
if(!IsPostBack)
{
fillStaffChoiceList();
}
}
(rowitem.Cells[6].FindControl("cbxSelect")`
Your looking for the checkbox in the wrong cell I guess. Don't you get an exeption on the checkbox? It shouldn't be available in cell 0.
This is an example of what can be used.
((CheckBox)gvPickStaff.Rows[i].FindControl("cbxSelect")).Checked
I hope that this can help also this is making it explicitly into a Check-box thus being able to return as is supposed to.
Use this in the check box:
<input type="checkbox" name="chk1" id="chk1" value='<%# Eval("idusers") %>' />
And when you want ids which is selected, use:
request("chk1");
It will return all data which is checked with comma(,) separated

Categories

Resources