I have a GridView that I populate. It appears correctly and shows the data. It contains a Checkbox column, and my intent is when the user clicks a button on the form, it iterates through the rows of the GridView, and totals up all the rows the user has selected by checking the CheckBox.
(I got the details of how to do this from http://asp.net-informations.com/gridview/checkbox.htm)
The problem comes at this point, and I've discovered that just before it gets to the line
foreach (GridViewRow row in grdItems.Rows)
grdItems.Rows.Count = 0, even though the GridView is currently displaying data.
The GridView:
<asp:GridView ID="grdItems" AutoGenerateColumns="false" runat="server" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Item_No" HeaderText="Item No" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
</Columns>
</asp:GridView>
The Button:
<asp:Button ID="cmdOK" runat="server" Text="Add" />
The Button Onclick:
protected void cmdOK_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SaveP2P();
}
}
The method the populates the GridView:
private void FillGrid()
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Snipped for privacy");
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandText = "Snipped for privacy";
cmd.Connection = conn;
System.Data.OleDb.OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter(cmd);
System.Data.DataSet ds = new System.Data.DataSet();
adp.Fill(ds);
adp.Dispose();
cmd.Dispose();
conn.Close();
grdItems.DataSource = ds;
grdItems.DataBind();
}
The ValidateForm() method which contains the code I'm struggling with
private bool ValidateForm()
{
bool result = true;
decimal TotalAmount = 0;
//If I display a message here, it shows grdItems.Rows.Count is 0
foreach (GridViewRow row in grdItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
TotalAmount += Decimal.Parse(row.Cells[2].Text);
}
}
}
decimal amount;
if (decimal.TryParse(txtAmount.Text, out amount))
{
if (amount > TotalAmount)
{
result = false;
}
}
else
{
result = false;
}
return result;
}
This sounds like a viewstate issue where when the page is posting back to the server, it is losing all the data in the grid. Have you tried enabling viewstate on your page to see if the gridview rows are returned.
Related
So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?
asp.net
<asp:GridView ID="MyGrid" runat="server"
DataKeyNames="No_" AutoGenerateColumns="false" Style="color: Black; border-collapse: collapse; margin-right: auto; display: table; text-align: center;" OnPageIndexChanging="MyGrid_PageIndexChanging" OnRowDataBound="MyGrid_RowDataBound" AllowPaging="True" OnPageIndexChanged="MyGrid_PageIndexChanged" PageSize="10" AllowCustomPaging="False">
<Columns>
<asp:BoundField DataField="No_" HeaderText="No_Encomenda" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
cs
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
List<string> MySelected;
protected void Page_Load(object sender, EventArgs e)
{
ButtonBack.Visible = false;
//GridView1.Visible = false;
con.Open();
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
if(IsPostBack == false)
{
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
}
if (IsPostBack == false)
{
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
refreshdata();
}
con.Close();
}
public void LoadGrid()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
In Page_Load code, I see that you are loading data in dropdownlist. When the page is submitted, Page_Load will execute and it will reload the data in the dropdown list. That's why selection goes off.
You should load the data in the dropdown list only during first load of the page. As you are doing with LoadGrid(). During post back the data of the dropdown and selection will be maintained if you don't reload them.
So I suggest following code change for loading data in dropdown list.
if(!IsPostBack)
{
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
I hope this will help you solve your problem.
I am trying to figure it out how can I display a dropDownList on a specific cell in the table right after clicking a button "Show DropDownlist" located on that cell.
This is the behind code , right now it is displaying the dropDownList at the last cell of each row. and I want to make it appear only when a button is clicked.
while (rdr.Read())
{
TableRow tRow = new TableRow();
myTable.Rows.Add(tRow);
for (int i = 0; i <= 4; i++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
if (i == 4)
{
tCell.Controls.Add(SM_List()); //Adding the dropdownlist
tRow.Cells.Add(tCell);
continue;
}
tCell.Text = rdr.GetString(i);
tCell.Attributes.Add("onmouseover", "this.style.cursor = 'pointer'; this.style.backgroundImage = ''; ");
tCell.Attributes.Add("onClick", "getData()");
tRow.Cells.Add(tCell);
}
/* iterate once per row */
}
I want to add this code, so it will be a button at first , instead of a drop down list :
Button bt = new Button();
bt.Text = "Switch";
bt.Click += new EventHandler(DropDownList_Show);
tCell.Controls.Add(bt);
But I am not sure how to display the DropDownList at the exact cell the button was located. and also I want to do some actions when Value was selected in the dropdownlist.
Can you please assist , I feel a little bit lost.
You can solve this issue easily by using GridView in ASP.NET.
Let say the GridView is declared as following in ASPX page.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" />
<asp:BoundField DataField="Token" />
<asp:BoundField DataField="Secret" />
<asp:ButtonField CommandName="ShowDropDown" Text="Show" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropDownList" runat="server" Visible="false">
<asp:ListItem Text="Valid" Value ="1"></asp:ListItem>
<asp:ListItem Text="Invalie" Value ="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Following is the method in code behind which populates the GridView.
private void BindGridView()
{
var tokens = new List<AccessToken>();
using (var conn = new SqlConnection("Server=somedbserver;Database=somedatabase;User Id=someuser;Password=somepassword;"))
{
using (var command = new SqlCommand())
{
command.Connection = conn;
command.CommandText = "SELECT Id, Token, Secret FROM Tokens";
command.CommandType = System.Data.CommandType.Text;
conn.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var token = new AccessToken();
token.Id = reader.GetInt32(0);
token.Token = reader.GetString(1);
token.Secret = reader.GetString(2);
tokens.Add(token);
}
}
}
}
GridView1.DataSource = tokens;
GridView1.DataBind();
}
And I am calling this method in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridView();
}
}
Following is the event handler of RowCommand event of GridView which will display the dropdown list in the column next to the button which is clicked.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "ShowDropDown")
{
var row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
//Using Cell[4] coz the Dropdownlist is in 5th column of the row.
//You need to replace 4 with appropriate column index here.
//Also replace "dropDownList" with the ID assigned to the dropdown list in ASPX.
var ddl = (DropDownList)row.Cells[4].FindControl("dropDownList");
if(ddl != null)
{
ddl.Visible = true;
}
}
}
You will able resolve your issue if you follow this approach.
This is a basic question but i didn't find appropriate answers : I have a dataset that is shown in dataGridview and it contains a column Is_Alarm of type bit (boolean) , i want to insert a Select all checkbox in that column.
I have seen many solutions but they are all about inserting a new checkbox in datagridView .
What i want is insert it after columns are shown , here's my code :
SqlDataAdapter adap= new SqlDataAdapter(select_query,con);
ds = new DataSet();
adap.Fill(ds, "Event_test");
dataGridView1.DataSource = ds.Tables[0];
I had same issue what I did might be useful for you
This is code used for gridview
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Next I Loaded data( MyTable field had id,username,email etc)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("Select * From UserInfo", con);
DataSet ds = new DataSet();
adap.Fill(ds);
con.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
For getting Ids of selected records I used few lines which is described here
http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx and modified in this way
protected void btnCheckSelected_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string ids = row.Cells[1].Text;
ListBox1.Items.Add(ids);
}
}
}
}
I have a asp.net form displaying the user details from an Oracle database, using a grid-view. I even managed to get a check-box field in the grid-view using the following template..
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chck"/>
</ItemTemplate>
</asp:TemplateField>
I want the admin to be able to select multiple entries using the check-boxes and perform a certain action on them. I tried using, for the delete operation, the following
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(GridView1.Rows[i].Cells[1].Value == true))
GridView1.Rows.RemoveAt[i];
}
However, this shows an error. Apparently, each check-box on each row must have its own unique index. How do I get to it?
Any sort of help will be appreciated. Thanx :)
You need to find control inside your gridview row using findControl
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb1 = (CheckBox)GridView1.Rows[i].FindControls("chck");
if(cb1.Checked)
GridView1.Rows.RemoveAt[i];
}
Use find control to get checkboxes:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chck = (CheckBox)GridView1.Rows[i].FindControl("chck");
if (chck != null)
{
if (chck.Checked)
{
GridView1.Rows.RemoveAt[i];
}
}
}
This is Aspx FIle :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView>
This is CS File :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = #"SELECT CategoryID, CategoryName, Approved FROM Categories";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
string cid = row.Cells[1].Text;
bool status = chkStatus.Checked;
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = "UPDATE Categories SET Approved = #Approved WHERE CategoryID = #CategoryID";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#Approved", SqlDbType.Bit).Value = status;
com.Parameters.Add("#CategoryID", SqlDbType.Int).Value = cid;
con.Open();
com.ExecuteNonQuery();
con.Close();
LoadData();
}
I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.