how to add button dynamically in gridview column? - c#

i have this code of gridview. how do i enable button to be add inside all column in each row other than first column using this code ? i dont have templatefield or others assign for gridview because i declare gridview display through this code. how can i achieve that ? this is my code :
`protected void Page_Load(object sender, EventArgs e)
{
//where request_date >= DATEADD(day,-8, GETDATE())
con.Open();
DataTable dtTemp = new DataTable();
cmd = new SqlCommand("SELECT a.request_date,a.prod_line,a.jo_no,a.qty,CONVERT(VARCHAR(10),a.need_by_date ,101) as need_by_date,b.process_id FROM CutPanelCard a LEFT JOIN CutPanelConfirmation b on b.req_id=a.req_id where request_date >= DATEADD(day,-8, GETDATE()) order by request_date", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTemp);
ViewState["Information"] = dtTemp;
try
{
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
string colValue4 = dtStudentdtl.Rows[i]["process_id"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "JO: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 + " Completion Status: " + colValue4;
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.DataSource = dtStudent;
GridView1.DataBind();
GridView_Row_Merger(GridView1);
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}`

Related

How to add button in each row of a grid view in asp.net for shopping cart.The button should delete the row

public void viewitemincart()
{
decimal total = 0;
int rowIndex = 0;
if (Session["Cart"] != null)
{
List<OrderDetail> otherorders = (List<OrderDetail>)Session["Cart"];
DataSet ds = new DataSet();
foreach (OrderDetail order in otherorders)
{
using (SqlConnection connection = new SqlConnection(DatabaseConnection.GetConnectionString()))
{
connection.Open();
string sql = "select "+ rowIndex+1 + " as no,itemName as Item, " + order.Quantity + " as Quantity, Price, " + order.Quantity + "*price as Total from tbl_item where itemId=" + order.ProductId;
SqlCommand sqlcmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
da.Fill(ds);
total += Convert.ToDecimal(ds.Tables[0].Rows[rowIndex]["Total"]);
rowIndex += 1;
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
lblGrand.Visible = true;
lblGrandTotal.Visible = true;
lblGrandTotal.Text = total.ToString();
}
}
//The code binds data in session["cart"] to Grid View.
//The code is used to add item in cart session and have it displayed in grid view.
//Now, i want to add a delete button on each row of the session and upon clicking the delete button the respective row needs to be deleted from the session.

Deleting multiple rows in datagridview using checkboxes-string was not recognized as a valid boolean

please help me I stuck in datagridview in c# winforms where my sql table looks like below
empcode-varchar(50)
fullname-varchar(50)
month-date
branch-varchar(50)
designation-varchar(50)
id-varchar(50)
accountno-nvarchar(50)
paymenttype-nvarchar(50)
basicsal-int
ca-int
hra-int
sa-int
totalsalary-int
allowanceid-int(IDENTITY COLUMN)
remark-nvarchar(50)
For this table i took two buttons one is viewdata and another is delete
my view data coding part working fine and is shown below:-
SqlDataAdapter da = new SqlDataAdapter("select * from allowance", cn);
dt = new System.Data.DataTable();
da.Fill(dt);
dg2.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dg2.Rows.Add();
dg2.Rows[n].Cells[0].Value = false;
dg2.Rows[n].Cells[1].Value = item["empcode"].ToString();
dg2.Rows[n].Cells[2].Value = item["fullname"].ToString();
dg2.Rows[n].Cells[3].Value = item["month"].ToString();
dg2.Rows[n].Cells[4].Value = item["branch"].ToString();
dg2.Rows[n].Cells[5].Value = item["designation"].ToString();
dg2.Rows[n].Cells[6].Value = item["id"].ToString();
dg2.Rows[n].Cells[7].Value = item["accountno"].ToString();
dg2.Rows[n].Cells[8].Value = item["paymenttype"].ToString();
dg2.Rows[n].Cells[9].Value = item["basicsal"].ToString();
dg2.Rows[n].Cells[10].Value = item["ca"].ToString();
dg2.Rows[n].Cells[11].Value = item["hra"].ToString();
dg2.Rows[n].Cells[12].Value = item["sa"].ToString();
dg2.Rows[n].Cells[13].Value = item["totalsalary"].ToString();
dg2.Rows[n].Cells[14].Value = item["allowanceid"].ToString();
dg2.Rows[n].Cells[15].Value = item["remark"].ToString();
}
and another button "delete" code is looks like this way:-
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(itemRow.Cells[14].Value.ToString()))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + itemRow.Cells[14].Value.ToString() + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (!itemRow.IsNewRow)
{
if ((bool)itemRow.Cells[0].EditedFormattedValue)
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = " + Convert.ToInt32(itemRow.Cells[14].Value) + "", cn);
DataTable bb = new DataTable();
da.Fill(bb);
try this
foreach (DataGridViewRow itemRow in dg2.Rows)
{
if (bool.Parse(Convert.Tostring(itemRow.Cells[14].Value)))
{
da = new SqlDataAdapter("DELETE FROM allowance WHERE allowanceid = '" + Convert.Tostring(itemRow.Cells[14].Value) + "'", cn);
DataTable bb = new DataTable();
da.Fill(bb);
}
}
MessageBox.Show("SuccessFully DELETED.....!");
wire this code in DaataError Event
private void DGData_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
if ((anError.Exception) is ConstraintException)
{
DataGridView grd1 = (DataGridView)sender;
grd1.Rows[anError.RowIndex].ErrorText = "an error";
grd1.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
}

Display gridview only when matching ID's match

I have applied a filter on dropdownlist selected value which matched the Project_id, Building_id and flat_id then gridview should display other wise not.
Now what I want is if ALL the id matches then only display the gridview.
Here is my code below:-
DataTable dt = new DataTable();
dt.Columns.Add("PROJECT_ID");
dt.Columns.Add("BUILDING_ID");
dt.Columns.Add("FLAT_ID");
DataView dView = new DataView(dt);
dView.RowFilter = "PROJECT_ID = " + ddlProject.SelectedValue + " AND BUILDING_ID = " + ddlBuilding.SelectedValue + " AND FLAT_ID = " + ddlUnit.SelectedItem.Text;
GrdBookingStatus.DataSource = dView.ToTable();
GrdBookingStatus.DataBind();
DisplayGrid();
GrdBookingStatus.Visible = true;
Currently it is showing if the ID's doesn't matches also
what condition should I check ?
DisplayGrid()
protected void DisplayGrid()
{
OracleCommand cmd = new OracleCommand("SELECT pn.property_name, pn.building, cd.flat_id, ab.flat_status, ab.COMMENTS " +
"FROM xxcus.xxacl_pn_projbuild_v pn INNER JOIN xxacl_pn_flat_status_his ab " +
"ON pn.project_id = ab.project_id AND pn.building_id = ab.building_id " +
"INNER JOIN xxacl_pn_flat_det_v cd ON cd.flat_id = ab.flat_id", ObjPriCon);
DataTable dtfillgrid = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dtfillgrid);
GrdBookingStatus.DataSource = dtfillgrid;
GrdBookingStatus.DataBind();
}
Your DisplayGrid() method reverts back the filter you had and displays all data.
Move the filter inside the DisplayGrid() method.
protected void DisplayGrid()
{
OracleCommand cmd = new OracleCommand("SELECT pn.project_id AS project_id, pn.property_name, pn.building, pn.building_id AS building_id, cd.flat_id AS flat_id, ab.flat_status, ab.COMMENTS " +
"FROM xxcus.xxacl_pn_projbuild_v pn INNER JOIN xxacl_pn_flat_status_his ab " +
"ON pn.project_id = ab.project_id AND pn.building_id = ab.building_id " +
"INNER JOIN xxacl_pn_flat_det_v cd ON cd.flat_id = ab.flat_id", ObjPriCon);
DataTable dtfillgrid = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dtfillgrid);
DataView dView = new DataView(dtfillgrid);
dView.RowFilter = "PROJECT_ID = " + ddlProject.SelectedValue + " AND BUILDING_ID = " + ddlBuilding.SelectedValue + " AND FLAT_ID = " + ddlUnit.SelectedItem.Text;
GrdBookingStatus.DataSource = dView.ToTable();
GrdBookingStatus.DataBind();
GrdBookingStatus.Visible = dView.ToTable().Rows.Count > 0;
}
I've also modified you SELECT statement to return pn.project_idand pn.building_id
protected void Button1_Click(object sender, EventArgs e)
{
if (ddl.SelectedIndex > 0)
{
int count = 0;
int selectedcheckbox = 0;
pfPL.Month = lblMonthId.Value;
pfPL.Year = lblYear.Value;
DataTable dt = pfBL.GetEmployeeCode(pfCPL);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i < dt.Rows.Count - 1)
{
for (int k = 0; k < grd.Rows.Count; k++)
{
string grdcode;
Label lbl = (Label)grd.Rows[k].FindControl("lblCode");
grdcode = lbl.Text;
CheckBox chk = (CheckBox)grd.Rows[k].FindControl("chkone");
e;
dbcode = dt.Rows[i][0].ToString();
if (dbcode.Trim() == grdcode.Trim())
{
chk.Checked = true;
count++;
}
}
}
}
}
}
}

Add row from datagridview1 to datagridview2

I have two datagridviews in one from. I need to get data from database to datagridview1 (using Select *from database...) then I want to add data from datagriwview to datagridview2 using Selected Rows.
First I wanted to solve this problem to get Selected Row's ID, when I select row in datagridview it shows in datagridview2, but when I select another row, it is updating in datagridview, it does not add as new row. I tried several ways but did not solve this problem, Is there anyone help me to solve this problem? Thanks
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32
(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["id"].Value);//3
try
{
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
dataGridView2.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Is quite simple the explanation: everytime that you make a double click to a datagridview1's cell you replace the old datatable with a new one. If you want append the result you can do something like this:
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if(dataGridView2.DataSource != null) {
DataTable pr = dataGridView2.DataSource as DataTable;
pr.Merge(dt);
dataGridView2.DataSource = pr;
}
else
dataGridView2.DataSource = dt;
Since you have all information in datagridview1 you should just copy the contents of the selected row into a new row for datagridrow2.
The DataGridView is based on a DataSet which contains DataTables.
The DataTable contains rows.
You cannot move a row from one table to annother.
Instead you have to create a new row and insert into the DataTable of DataGridView2
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow.Cells["Id"].Value != null)
{
int Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
MySqlConnection start = new MySqlConnection(baglanti);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + Id + "'";
start.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
int idx = dataGridView2.Rows.Count - 1;
dataGridView2.Rows.Add(dt.Rows.Count);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int rVal = (idx + i) + 1;
dataGridView2.Rows[rVal].Cells["id"].Value = dt.Rows[i]["id"].ToString();
dataGridView2.Rows[rVal].Cells["muayine_adi"].Value = dt.Rows[i]["muayine_adi"].ToString();
dataGridView2.Rows[rVal].Cells["sabit_qiymet"].Value = dt.Rows[i]["sabit_qiymet"].ToString();
}
}
start.Close();
}
}

no row at position 0

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

Categories

Resources