How to get column name and create string variable dynamically? - c#

Through Edit link button I'm able to edit record using code below . As you can see here number of columns are 4 , for fixed column number this code is fine but In my condition Column numbers are not fixed ,they may 4 or may be 5 for next insert. How can I get column names and create that number of string variable, so that I can assign string values to particular field ?
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string a = (row.Cells[3].Controls[0] as TextBox).Text;
string b = (row.Cells[4].Controls[0] as TextBox).Text;
string c = (row.Cells[5].Controls[0] as TextBox).Text;
string d = (row.Cells[6].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[row.RowIndex]["Column0"] = a;
dt.Rows[row.RowIndex]["Column1"] = b;
dt.Rows[row.RowIndex]["Column2"] = c;
dt.Rows[row.RowIndex]["Column3"] = d;
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
btnGetSelected.Visible = true;
}

Do you mean you need the columns names of the GridView?
You could use either of these
gv.HeaderRow.Cells[i].Text
gv.Rows[0].Cells[i].Text
Reference
It you want column names of DataTable use
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();

This worked for me.
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
DataTable dt = ViewState["dt"] as DataTable;
int j=0;
for (int i = 3; i < row.Cells.Count; i++)
{
string a = (row.Cells[i].Controls[0] as TextBox).Text;
dt.Rows[row.RowIndex][j] = a;
j++;
}
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
btnGetSelected.Visible = true;
}

Related

Gridview cells shows blank value in Asp.NET

I'm creating website in Asp.net (Framework 4.0).
In this website I have taken a Gridview which is filled with data on page load.
Now I'm trying to Insert data from Gridview to database on button click. While inserting into database GridView Cells shows blank values.
Code as follows for GridView Binding
void BindGrid()
{
GridView1.DataSource = obj3.GetCart(sid, uid);
GridView1.DataBind();
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
GridView1.Visible = false;
lblCartCount.Visible = true;
lblCartCount.Text = " No Items In Cart";
}
else
{
GridView1.Visible = true;
GridView1.FooterRow.Cells[3].Text = "Total Price";
GridView1.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Cells[9].Text = totals.ToString();
totprice = Convert.ToInt32(totals.ToString());
totals = 0;
lblCartCount.Visible = false;
}
}
Code for Insert button click for Insert data from Gridview to database.
protected void btnOrderNow_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
BindGrid();
val1 = obj4.AddOrderItem(orderid, Convert.ToInt32(g1.Cells[2].Text),
Convert.ToInt32(g1.Cells[5].Text), Convert.ToInt32(g1.Cells[4].Text),
Convert.ToInt32(g1.Cells[6].Text), Convert.ToInt32(g1.Cells[7].Text),
g1.Cells[0].Text, Convert.ToInt32(g1.Cells[1].Text));
}
}
I found my answer by myself. The code for Insert data from Gridview to database has some following changes .
protected void btnOrderNow_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
string sss = (((Label)(g1.Cells[g1.RowIndex].FindControl("lblSession"))).Text.Trim());
int uuu = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("Label5"))).Text.Trim());
int itemid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemId"))).Text.Trim());
int priceid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPriceId"))).Text.Trim());
int quantity = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemQuantity"))).Text.Trim());
int price = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPrice"))).Text.Trim());
int bprice = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblBulkPrice"))).Text.Trim());
val2 = obj4.OrderTempCartUpdate(sss, uuu);
}
}
In this instead of taking only g1.Cells[0].text wasn't able to find particular row index . So I have added
(((Label)(g1.cells[g1.RowIndex].FindControl("LabelName"))).
instead of g1.Cells[0].text;

How to add new row on click winforms

I have a winforms application that I am developing, I have hit a dead end. What I am trying to do is on each "click", add a new row to my DataTable with the values input in the form. This Datatable is the DataSource for my DataGridView. Can someone point me in the right direction on how this can be achieved.
Articles I looked at:
How to add new row to datatable gridview
My code:
private void btnAdd_Click(object sender, EventArgs e)
{
//inserting into order table
DataTable dt = new DataTable();
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
On each click you are creating a new DataTable which would be with just one row, You need to create DataTable once and then just keep adding rows to in the click. Define your DataTable at class level and then in your event just add a new row to it.
DataTable dt = new DataTable(); //at class level
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTableColumns();
//.... your code
}
Then have a method to create table structure, call that method once from your From_Load event.
private void CreateDataTableColumns()
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
}
Later add rows to your class level DataTable in Add event.
private void btnAdd_Click(object sender, EventArgs e)
{
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
(I believe you are doing something with the exception object in your catch block, like logging, showing message to user etc)

updating datatable from gridview updating event

I have a datatable that I am populating with data, however if I want to edit the row I am getting an error
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
The code that populates the gridview is
public void addTochkout(string type, string no)
{
DataTable dt = (DataTable)Session["table_chkout"];
DataRow dr = dt.NewRow();
dr[0] = type;
dr[1] = no;
dt.Rows.Add(dr);
Session["table_detail"] = dt; //save dt to new session
gridbind();
}
public void gridbind()
{
//gridview
if (Session["table_detail"] != null)
{
DataTable dt = (DataTable)Session["table_detail"];
if (dt.Rows.Count > 0)
{
chkoutDetail.DataSource = dt;
chkoutDetail.DataBind();
string countitems = dt.Rows.Count.ToString();
Session["cart_counter"] = countitems;
}
}
else
{
chkoutDetail.DataSource = null;
chkoutDetail.DataBind();
}
}
Now, when I try and update the gridview I am getting the error above from the line
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
The entire code block where is erroring is
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
//Update the values.
GridViewRow row = chkoutDetail.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Price"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
//Reset the edit index.
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
}
I would be very grateful if you could help me solve this issue.
Simon
Note that when you have the Edit option enabled, the first and second cells of the edit mode of the row in the grid view are linkbuttons(Update and Cancel). So probably you have to change the index while getting the textbox in the row
//Cell number 2 for the first textbox. 0 for update link and 1 for cancel link
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
I had figured out my issue just after posting the, but it wouldn't allow me to answer the question.
heres my solutions
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
// //Update the values.
string type = e.NewValues[0].ToString();
string qty = e.NewValues[1].ToString();
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
dt.Rows[e.RowIndex]["TicketType"] = type;
dt.Rows[e.RowIndex]["TicketNo"] = qty;
dt.AcceptChanges();
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
int value1 = Convert.ToInt32(ddtickettype.SelectedItem.Value);
int value2 = Convert.ToInt32(ddTicketno.SelectedItem.Value);
string tType = ddtickettype.SelectedItem.Text;
string tNo = ddTicketno.SelectedItem.Text;
int prevTotal = Convert.ToInt32(lblAmount.Text);
int total = (value1 * value2) + prevTotal;
Session["TotalAmount"] = total.ToString();
if (Session["TotalAmount"] != null)
{
lblAmount.Text = Session["TotalAmount"].ToString();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}

How to get Value of specific cell of datagridview in Winform application

I have a dataGridView which contains the check-boxes in its first column. Now as per my requirement i have to get the value of Employee No column for the row whose checkbox has been clicked on another button click event.Also how to get the value for multiple checkbox selected .
Here is my code..
private void btn_load_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
}
Please help me .Thanks in advance..
You can also use the DataSource property:
private void btn_Click(object sender, EventArgs e)
{
int[] employeeIds = (dataGridView1.DataSource as DataTable).Rows
.Cast<DataRow>()
.Where(r => (bool)r["Select"])
.Select(r => Convert.ToInt32(r["Employee No"]))
.ToArray();
}
and use the System.Linq namespace.
Because you have bound your DataTable to the grids DataSource, you could make dt a class variable and use that to check the selected ones.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dt;
private void btn_load_Click(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Employee No");
dt.Columns.Add("Employee Name");
dt.Columns.Add("Join Date");
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr["Select"] = false;
dr["Employee No"] = 1000 + i;
dr["Employee Name"] = "Employee " + i;
dr["Join Date"] = DateTime.Now.ToString("dd/MM/yyyy");
dt.Rows.Add(dr);
}
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.DataSource = dt;
}
private void btn_Click(object sender, EventArgs e)
{
//I need the Employee Id values here
foreach (DataRow row in dt.Rows)
{
if ((bool)row["Select"] == true)
{
}
}
}
}
Suppose to have a global variable in your form class declared as
List<int> empIDs = new List<int> empIDs();
Now in your click event you could write
private void btn_Click(object sender, EventArgs e)
{
empIDs.Clear();
foreach(DataGridViewRow r in dgv.Rows)
{
DataGridViewCheckBoxCell c = r.Cells["Select"] as DataGridViewCheckBoxCell;
if(Convert.ToBoolean(c.Value))
empIDs.Add(Convert.ToInt32(r.Cells["Employee No"].Value));
}
}
At the end of the click event the global variable will be filled with the ID of the employees that have their SELECT cell clicked

cannot bind data to gridview combobox in datagridview at editing mode

The following is my code for row editing event.
protected void branchgrid_RowEditing(object sender, GridViewEditEventArgs e)
{
if (TextBox1.Text == "")
{
workingdaygrid.EditIndex = e.NewEditIndex;
bindworkingday();
GridViewRow row = workingdaygrid.Rows[e.NewEditIndex];
DropDownList dl = row.FindControl("Workingdaytype") as DropDownList;
DataTable worktype = inter.bindworkdaytype();
dl.DataSource = worktype;
dl.DataTextField = "Workingday_type";
dl.DataValueField = "Time_id";
dl.DataBind();
}
else
{
string datetime = TextBox1.Text;
comp.DATETIME = Convert.ToDateTime(datetime);
DataTable result = inter.searchworkday(comp);
workingdaygrid.DataSource = result;
workingdaygrid.DataBind();
workingdaygrid.EditIndex = e.NewEditIndex;
GridViewRow row = workingdaygrid.Rows[e.NewEditIndex];
DropDownList dl = row.FindControl("Workingdaytype") as DropDownList;
DataTable worktype = inter.bindworkdaytype();
//string datetime = TextBox1.Text;
dl.DataSource = worktype;
dl.DataTextField = "Workingday_type";
dl.DataValueField = "Time_id";
dl.DataBind();
}
after filtration using search button, I am trying editing the particular row(data) but i cannot get the gridview combobox value. it is blank. but in the full databind(first if condition) combobox value is binded.
my seach button code is
string datetime = TextBox1.Text;
comp.DATETIME = Convert.ToDateTime(datetime);
DataTable result = inter.searchworkday(comp);
workingdaygrid.DataSource = result;
workingdaygrid.DataBind();

Categories

Resources