checkboxed selected rows from gridview1 to gridview2 ASP.NET C# - c#

As title said it all anyway I have a table is sql-server products.
Which has product id, name,price and cetegory.
what i did is i get data into 1st GridView category wise, and what i want is when i checked that particular row or multiple row and click select button it shuld show product name and price in 2nd gridview.
But what its do is it override the next selected item to previously selected item in 2nd gridview and shows onlu one row not multiple selected items.
can anybody help me ??
here is a code
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;
if (chbox.Checked == true)
{
string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "select prod_name,price from products where prod_id = '" + GridView1.Rows[i].Cells[1].Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
}

You binded the grid too many times.
protected void Button1_Click(object sender, EventArgs e) {
List<string> checkedIDs = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++) {
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;
if (chbox.Checked == true)
{
checkedIDs.Add("'" + GridView1.Rows[i].Cells[1].Text + "'");
}
}
string conn = ConfigurationManager.ConnectionStrings["Test_T3ConnectionString2"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "select prod_name,price from products where prod_id in (" + string.Join(",", checkedIDs.ToArray()) + ")";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}

Related

Filter gridview based on the checked value from the another gridview

I have two GridView. First is called "gvImage" which is the category gridview with checkbox for selection. Second GridView is called "GridView1", the Second GridView populates basing on the value selected in the First GridView, here I am able to populate the record in Second GridView only for one category checked (selected) from the First GridView, but when I check (select) multiple category from the First GridView(gvImage) then it is not populating the multiple category record in the Second GridView(GridView1). Please help me to get this, below is my Code behind:
protected void btn_Submit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
String strConnString = ConfigurationManager.ConnectionStrings["CONNECTION1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string str = "SELECT * FROM AllProduct WHERE PId =#PId";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("#PId", row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text);
//this.ExecuteQuery(cmd, "SELECT");
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
GridView1.Enabled = true;
}
}
}
else if (objDs.Tables[0].Rows.Count == 0)
{
GridView1.DataSource = null;
GridView1.Visible = false;
}
}
}
}
}
The problem is that you bind the second grid for each selected checkbox which will essentially always replace the data that has been bound, so that you only see the results for the last selected checkbox. You need to combine the results and bind outside the foreach
protected void btn_Submit_Click(object sender, EventArgs e)
{
DataTable combinedDataTable;
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
DataTable data = //Data from database for this checkbox
if(combinedDataTable != null)
combinedDataTable.Merge(data);
else
combinedDataTable = data;
}
}
}
GridView1.DataSource = combinedDataTable;
GridView1.DataBind();
}
or even better, just collect which checkboxes are checked first, and then get the results in one query:
protected void btn_Submit_Click(object sender, EventArgs e)
{
List<string> selectedCheckboxes = new List<string>()
foreach (GridViewRow row in gvImage.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
selectedCheckboxes.Add(row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text);
}
}
}
String strConnString = ConfigurationManager.ConnectionStrings["CONNECTION1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string str = "SELECT * FROM AllProduct WHERE PId in ";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
List<string> parametersNames = new List<string>();
for (int i = 0; i < selectedCheckboxes.Count; i++)
{
var parameterName = "#PId" + i;
cmd.Parameters.AddWithValue(parameterName, selectedCheckboxes[i]);
parametersNames.Add(parameterName);
}
str += "(" + String.Join(",", parametersNames) + ")";
str += " AND TransactionDate BETWEEN #From AND #To";
cmd.Parameters.AddWithValue("#From", DateTime.Parse(txtFrom.Text));
cmd.Parameters.AddWithValue("#To", DateTime.Parse(txtTo.Text));
cmd.CommandText = str;
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
GridView1.Enabled = true;
}
}
}
else if (objDs.Tables[0].Rows.Count == 0)
{
GridView1.DataSource = null;
GridView1.Visible = false;
}
}

GridView Not showing when i delete the all rows from database table

i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx

Is there any Way to show Empty GridView On pageLoad event?

Hope You all Are Fine
Can any one help me kindly i have a grid view that fetch tha record from database but show all the previous data which i entered by the grid but now i want to show the all data which i entering till the pageload even called, when page load that should not show all the entered records.
Thanks in Advance
Here is my code behind work
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("select distinct T1.SlpCode,T1.SlpName,T3.StepId,T3.Descript from OSLP T1 left join OPR1 T2 on T1.SlpCode=T2.SlpCode right join OOST T3 on T3.StepId=t2.Step_Id ", connection);
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
If you want to keep the grid empty on page load event, then do not write the code to bind it on Page Load event, instead write the code on"Add Button" click event(if that's what you want).
For showing empty record Grid You can Use EmptyDataTemplate.
For more you can try this Link

Search checkbox values in gridview

I have a dropdown list with checkbox in the page and when I select multiple options and search its not returning all the selected values in the grid. It returns only one selected value. Here is the code I use it for search. Any suggestions or change in the code. I have binded one gridview column to that checkbox. Checkbox is present outside the gridview. Any suggestions or change in the code?
<asp:CheckBoxList ID="cblGroup" Style="vertical-align: baseline" runat="server" CssClass="chkbox">
</asp:CheckBoxList>
Below is the code on button search I am trying to fetch the checkbox values
protected void btnSearchGroup_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select * from AppInvent_Test where Designation= '" + cblGroup.SelectedValue + "'", con);
SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
Adpt.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
OK as mentioned by Sudhakar, Try this
protected void btnSearchGroup_Click(object sender, EventArgs e)
{
string selectedValues = string.Empty;
foreach (ListItem item in cblGroup.Items)
{
if (item.Selected)
selectedValues += "'" + item.Value + "',";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);//To remove the last comma;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select * from AppInvent_Test where Designation in (" + selectedValues + ")", con);
SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
Adpt.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

First GridView dissapears when binding a second GridView in code

I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}
you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.

Categories

Resources