I am Not getting text field values into grid view. Only row increases but I do not get the text.
This is the code that I have for the purpose.
DataTable dt1 = new DataTable();
bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridVIEWData();
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
}
protected void gobtn_Click(object sender, EventArgs e)
{
if (Session["dtInSession"] != null)
dt1 = (DataTable)Session["dtInSession"];
DataRow dr = dt1.NewRow();
dr["Product"] = DropDownList1.SelectedItem;
dr["Size"] = DropDownList2.SelectedItem;
dr["Case"] = casetxt.Text;
dr["Weight"] = TextBox1.Text;
dr["Price"] = TextBox2.Text;
dt1.Rows.Add(dr);
Session["dtInSession"] = dt1;
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
private void gridVIEWData()
{
dt1.Columns.Add("Product", typeof(string));
dt1.Columns.Add("Size", typeof(string));
dt1.Columns.Add("Case", typeof(string));
dt1.Columns.Add("Weight", typeof(string));
dt1.Columns.Add("Price", typeof(string));
Session["dtInSession"] = dt1;
}
Please Can any one help me
**I hope you looking for something like this**
protected void BindGridview1()
{
DataTable dtt = new DataTable();
DataTable dt = (DataTable)Session["od"];
dtt.Columns.Add("BookingNO", typeof(string));
dtt.Columns.Add("ItemName", typeof(string));
dtt.Columns.Add("Size", typeof(string));
dtt.Columns.Add("Unit", typeof(string));
dtt.Columns.Add("Price", typeof(string));
dtt.Columns.Add("PendingQty", typeof(string));
for (int i = 0; i < dtt.Rows.Count; i++)
{
DataRow dr = dtt.NewRow();
dr["BookingNO"] = string.Empty;
dr["ItemName"] = string.Empty;
dr["Size"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Price"] = string.Empty;
dr["PendingQty"] = string.Empty;
dtt.Rows.Add(dr);
}
dtt = dt;
gvDetails.DataSource = dtt;
gvDetails.DataBind();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
TextBox BookingNO = (TextBox)gvDetails.Rows[i].FindControl("BookingNO");
TextBox ItemName = (TextBox)gvDetails.Rows[i].FindControl("ItemName");
TextBox Size = (TextBox)gvDetails.Rows[i].FindControl("Size");
TextBox Unit = (TextBox)gvDetails.Rows[i].FindControl("Unit");
TextBox Price = (TextBox)gvDetails.Rows[i].FindControl("Price");
//TextBox DueDate = (TextBox)gvDetails.Rows[i].FindControl("DueDate");
TextBox PendingQty = (TextBox)gvDetails.Rows[i].FindControl("PendingQty");
BookingNO.Text = Session["BookingNO1"].ToString();
ItemName.Text = dt.Rows[i]["ItemName"].ToString();
Size.Text = dt.Rows[i]["Size"].ToString();
Unit.Text = dt.Rows[i]["Unit"].ToString();
Price.Text = dt.Rows[i]["Price"].ToString();
//DueDate.Text = dt.Rows[i]["DueDate"].ToString();
PendingQty.Text = dt.Rows[i]["PendingQty"].ToString();
}
}
Related
I'm trying to filter a datagridview that has been bound to a dataset. The thing is, when I type data into my textbox, the app stops and the error is that the column I'm trying to filter doesn't exist. I tried populating the datagridview with a string query and filtering works properly, but I can't update the datagridview (I don't know why). That's why I'm populating it with a dataset instead of the query. Any suggestions? This is what I have:
DataTable dt = new DataTable("Items");
private void LoadDataGrid()
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Items.ItemID AS #, Items.SerialNo AS 'SERIALNO', Items.Description AS DESCRIPTION, Items.MaxVoltage, Items.FrameSize, Items.ArrivalDate, Items.DepartureDate, Items.Notes, Items.MechType, Items.[Fix-Drawout], CONCAT(Location.Rack, Location.Row, Location.Columnn, Location.Position) AS LOCATION, ItemStatus.Description AS STATUS, Type.Description AS TYPE, Manufacturers.Description AS MANUFACTURERS FROM Items INNER JOIN Location ON Items.LocationID = Location.LocationID INNER JOIN ItemStatus ON Items.Status = ItemStatus.StatusID INNER JOIN Type ON Items.TypeID = Type.TypeID INNER JOIN Manufacturers ON Items.ManufacturerID = Manufacturers.ManufacturerID", AEAcnn))
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
This is the filter expression I'm using (with a combobox)
private void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
dataGridView1.DataSource = dv.ToTable();
}
}
The app crashes when the column TYPE can't be found, even though the name is actually TYPE.
Try something like this:
if (dt.Rows.Count > 0)
{
string str = string.Format("[TYPE] LIKE '%{0}%'", textBox14.Text.Replace("'", "''"));
dt.CaseSensitive = false;
DataTable dt1 = dt.Select(str).CopyToDataTable();
dataGridView1.DataSource = dt1;
}
Despite the unconventional column names, I don't see anything incorrect with the code if you are getting past filling the data table with the adapter, which apparently is the case since you get no error until the keypress event. Since we can't see the entire context of the code I suspect you are not binding the data you think you are, or the binding is changing somewhere else that you haven't noticed.
See this LINQPad script for proof it works:
Form frm = new Form();
DataTable dt = new DataTable("Items");
DataGridView dataGridView1 = new DataGridView();
TextBox textBox14 = new TextBox();
TextBox cmbFilterSearch = new TextBox();
void Main()
{
PopulateDataTable(dt);
BuildForm(frm, dt);
Application.Run(frm);
}
void BuildForm(Form frm, DataTable dt)
{
frm.Height = 500;
frm.Width = 900;
cmbFilterSearch.Text = "TYPE";
frm.Controls.Add(cmbFilterSearch);
textBox14.Text = "filter...";
textBox14.Location = new Point(0,50);
frm.Controls.Add(textBox14);
textBox14.KeyPress += txtFilter_KeyPress;
dataGridView1.DataSource = dt;
dataGridView1.Location = new Point(0, 80);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.Width = 800;
frm.Controls.Add(dataGridView1);
}
void txtFilter_KeyPress(object sender, KeyPressEventArgs e)
{
if (cmbFilterSearch.Text == "TYPE")
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("TYPE LIKE '%{0}%'", textBox14.Text);
Console.WriteLine(dv.RowFilter);
dataGridView1.DataSource = dv.ToTable();
}
}
void PopulateDataTable(DataTable dt)
{
dt.Columns.Add("#", typeof(int));
dt.Columns.Add("'SERIALNO'", typeof(string));
dt.Columns.Add("DESCRIPTION", typeof(string));
dt.Columns.Add("MaxVoltage", typeof(string));
dt.Columns.Add("FrameSize", typeof(string));
dt.Columns.Add("ArrivalDate", typeof(DateTime));
dt.Columns.Add("DepartureDate", typeof(DateTime));
dt.Columns.Add("Notes", typeof(string));
dt.Columns.Add("MechType", typeof(string));
dt.Columns.Add("Fix-Drawout", typeof(string));
dt.Columns.Add("LOCATION", typeof(string));
dt.Columns.Add("STATUS", typeof(string));
dt.Columns.Add("TYPE", typeof(string));
dt.Columns.Add("MANUFACTURERS", typeof(string));
DataRow row = dt.NewRow();
row[0] = 1;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "KEYWORD";
row[12] = "ACME";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 2;
row[1] = "43537953";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Reserved Word";
row[12] = "Conglomico";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 3;
row[1] = "9083290823";
row[2] = "Mares eat oats";
row[3] = "12v";
row[4] = "60";
row[5] = DateTime.Now;
row[6] = DateTime.Now.AddDays(7);
row[7] = "and does eat oats";
row[8] = "and little lambs";
row[9] = "eat ivy.";
row[10] = "Cancelled";
row[11] = "Identifier";
row[12] = "Enormico";
dt.Rows.Add(row);
}
Try it this way.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataView dv ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Filter DataView");
adapter.Dispose();
command.Dispose();
connection.Close();
dv = new DataView(ds.Tables[0], "Product_Price < = 3000", "Product_Name", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Adding data in datatable from dropdown and displaying it in gridview. Then I am deleting a row and maintaining the ViewState but after deleting one row and mapping my values again I get the earlier state of the table in the gridview with duplicated records.
Here's the code:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
//dt = new DataTable("tblTest");
//dt = ViewState["updatedtbl"] as DataTable;
DataColumn dc1 = new DataColumn();
dc1.DataType = typeof(String);
dc1.ColumnName = "A";
DataColumn dc2 = new DataColumn();
dc2.DataType = typeof(String);
dc2.ColumnName = "B";
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
//ViewState["dt"] = dt;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable();
DropDownList1.Items.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName));
}
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["A"] += DropDownList1.SelectedItem.Value + "|";
Session["B"] += DropDownList2.SelectedItem.Value + "|";
CreateTable();
}
public void CreateTable()
{
string[] sa = Session["A"].ToString().Split('|');
string[] sb = Session["B"].ToString().Split('|');
int recordnum = sa.Length;
for (int j = 0; j < recordnum - 1; j++)
{
DataRow dr = dt.NewRow();
dr["A"] = sa[j].ToString();
dr["B"] = sb[j].ToString();
dt.Rows.Add(dr);
}
ViewState["tbl"] = dt;
BindGrid();
}
protected void BindGrid()
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dx = ViewState["tbl"] as DataTable;
//DataTable dx = dt;
if (dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
ViewState["updatedtbl"] = dx;
}
else //To check which portion of code is being executed
{
Label1.Text = "Deleted";
Label2.Text = dx.Rows.Count.ToString();
}
}
In delete event you are reassigning the updated datatable to different viewstate with name updatedtbl. You should assign it to ViewState["tbl"].
if(dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
//ViewState["updatedtbl"] = dx; <<---- pay attention here
ViewState["tbl"] = dx; <<---- pay attention here
}
I have a Grid view containing 3 drop down lists and 3 text boxes each and a button. my drop down lists are populating data from data base. When i click on the button to add new row after filling the initial row. it sets the first row values fine and adds a new row. but the new row has no items in drop down lists this is my problem. secondly when i click the button again for adding third row it even looses the value of first row filled and same problem comes with first row that there are no items in drop down lists.
void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox and dropdown lists values
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box3.Text;
Session["list1"] = dtCurrentTable.Rows[i - 1]["Column1"];
Session["list2"] = dtCurrentTable.Rows[i - 1]["Column2"];
Session["list3"] = dtCurrentTable.Rows[i - 1]["Column5"];
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
list1.DataSource = bindddl();
list1.DataValueField = "Item_name";
list1.DataTextField = "Item_name";
list1.DataBind();
list1.Items.Insert(0, new ListItem("--Select--", "0"));
list2.DataSource = binddd2();
list2.DataValueField = "Sub_item";
list2.DataTextField = "Sub_item";
list2.DataBind();
list2.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(1, new ListItem("Yes", "1"));
list3.Items.Insert(2, new ListItem("No", "2"));
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
list1.Text = Session["list1"].ToString();
list2.Text = Session["list2"].ToString();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
list3.Text = Session["list3"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
// Response.Write(Session["list1"]);
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
Fillcombo,Fillcombo1 are functions which are populating Drop down lists 1,2 through data base Fillcombo2 is populating it has two items yes' and 'no'.
My Fillcombo functions are like this
try
{
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{conn.Open();
SqlCommand cmdstr = new SqlCommand("SELECT [Sub_item] FROM [ADS].[dbo].[Accounts_heads_data]", conn);
// SqlCommand cmdstr = new SqlCommand("SELECT * FROM [ADS].[dbo].[Accounts_heads_data] ", conn);
SqlDataAdapter da2 = new SqlDataAdapter(cmdstr);
DataSet ds2 = new DataSet();
da2.Fill(ds2);
DropDownList DropDownList2 = (DropDownList)Gridview1.Rows[0].FindControl("DropDownList2");
DropDownList2.DataValueField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataTextField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataSource = ds2.Tables[0];
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--Select--", "0"));
ViewState["fc1"] = ds2;
conn.Close();
}
}
catch (Exception ex)
{
Label1.Visible = true;
}
}
check by comenting
SetPreviousData(); line from
AddNewRowToGrid function
OR
in AddNewRowToGrid function only set data for new row and call SetPreviousData(); function in first row of AddNewRowToGrid function.
I compiled your code with some test data and changed the code a bit. Try following and see.
void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count-1; i++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[i].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[6].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column3"] = box1.Text;
dtCurrentTable.Rows[i]["Column4"] = box2.Text;
dtCurrentTable.Rows[i]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column6"] = box3.Text;
}
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
Fillcombo();
Fillcombo1();
Fillcombo2();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
if (i < dt.Rows.Count - 1)
{
list1.ClearSelection();
list1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
list2.ClearSelection();
list2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;
list3.ClearSelection();
list3.Items.FindByText(dt.Rows[i]["Column5"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
I want to fill grid view with textbox and dropddown list values recursively on button click.Currently it is binding only once.I am new to ASP.NET.Help would be highly appreciated
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
for (int intCnt = 0; intCnt < grd.Rows.Count - 1; intCnt++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Resource"] = grd.Rows[intCnt].Cells[0];
dr["available"] = grd.Rows[intCnt].Cells[1];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Please try this hope it will help
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
foreach(GridViewRow row in grd.Rows)
{
dr = dt.NewRow();
dr["Resource"] = row.Cells[0].Text;
dr["available"] =row.Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Use following code:
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = defineColumn();
DataRow dr;
foreach (GridViewRow grow in grdChMedicine.Rows)
{
dr = dt.NewRow();
dr["Diagnosis"] = grow.Cells[1].Text;
dr["DiagnosisId"] = grow.Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Diagnosis"] = ddldiagnosis.SelectedItem.ToString();
dr["DiagnosisId"] = ddldiagnosis.SelectedValue;
dt.Rows.Add(dr);
ViewState["ChMedicine"] = dt;
grdChMedicine.DataSource = dt;
grdChMedicine.DataBind();
}
private DataTable defineColumn()
{
DataTable dt = new DataTable();
dc = new DataColumn("Diagnosis");
dt.Columns.Add(dc);
dc = new DataColumn("DiagnosisId");
dt.Columns.Add(dc);
return dt;
}
I am trying to add row in DataTable CartDT using row[], which is a string array.
DataTable CartDT = new DataTable();
public void DataTableColumn()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
string[] row = new string[5];
row[0] = arg[0]; //Product_Name
row[1] = arg[1]; //Product_ID
row[2] = itemQuantity.Text; //OrderQTY
row[3] = arg[2]; //Price
row[4]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Now when I execute it, it gives the error that "Input array is longer than the number of columns in this table"
The array row[] has exactly 5 elements in it & also DataTable CartDT has also 5 columns.
Now i am not able to find exactly where i am wrong.
Please help me to find the bug.
Thanx in advance.
Instead do this
DataRow dr = CartDT.NewRow();
Then
dr[0] = arg[0];
and so on. In the end
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
This way the instance of Row will have CartDT schema.
DataTable CartDT = new DataTable();
public void CreateDataTableColumns()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
if (CartDT.Columns.Count = 0)
{
CreateDataTableColumns();
}
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity =
(TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow dr = CartDT.NewRow();
dr[0] = arg[0]; //Product_Name
dr[1] = arg[1]; //Product_ID
dr[2] = itemQuantity.Text; //OrderQTY
dr[3] = arg[2]; //Price
dr[4] = (Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString(); // calculate total price
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Debug, and break on
CartDT.Rows.Add(row);
and see how many columns are in CartDT; I think you don't call DataTableColumn() at the right time.
Your code having to do with row insertion works just fine
DataTable CartDT = new DataTable();
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
string[] row = new string[5];
row[0] = "1"; //Product_Name
row[1] = "2"; //Product_ID
row[2] = "3"; //OrderQTY
row[3] = "4"; //Price
row[4] = "5";// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
for (int i = 0; i < 5; i++)
{
Console.WriteLine(CartDT.Rows[0][i]);
}
Console.Read();
Try Below Code:
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow row = CartDT.NewRow();
row["Product_Name"] = arg[0]; //Product_Name
row["Product_ID"] = arg[1]; //Product_ID
row["OrderQTY"] = itemQuantity.Text; //OrderQTY
row["Price"] = arg[2]; //Price
row["TotalPrice"]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();
CartDt.Rows.Add(row);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}