Adding row by row in GridView in runtime - c#

I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}

//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();

add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();

Related

How to get all data in gridcontrol by one click

How to use loop to read all records by one click on the button. I have to print many reports.For each row in the table I need to create a report. And read until the last row of the table . My idea is using loop or index table but i don't know how to do it. This is my code:
private void btnin_Click(object sender, RoutedEventArgs e)
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdata1 WHERE Customers = '" + cbbcustomer.Text + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cnn.Close();
XtraReport1 report = new XtraReport1();
report.DataSource = dt;
report.ShowPreviewDialog();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
}
You could iterate through the Datatable
foreach(DataRow row in dt.Rows)
{
DataTable dtrow = new DataTable();
dtrow = dt.Clone();
dtrow.ImportRow(row);
XtraReport1 report = new XtraReport1();
report.DataSource = dtrow;
//report.ShowPreviewDialog(); Not sure what happens here but maybe a print method is better suited?
}
Basically for each row you create a datatable with the same structure and import one row. Then its assigned as your datasource. This will iterate through all rows.
For some reasons, I had to change something in my code. I used Mark Vance's code but it didn't work:
DataTable a = new DataTable();
a = ((DataView)ctrlgridviewdulieu0.ItemsSource).ToTable();
foreach (DataRow row in a.Rows)
{
DataTable dtrow = new DataTable();
dtrow = a.Clone();
dtrow.ImportRow(row);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdulieu2 WHERE Khachdat = N'" + dtrow.ToString() + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
XtraReport1 report = new XtraReport1();
report.DataSource = dt1;
// report.Print();
cnn.Close();
report.ShowPreviewDialog();
}
catch (Exception ex)
{
cnn.Close();
MessageBox.Show(ex.Message);
}
}

C# System.Data.DataRowView

I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}

DataGridView add column by code

I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();

How to show all the rows in datagridview?

DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;

how to update GridView row at once in sql database

I have DLL class to call the table
public DataTable GetTemTableValue(string TableName)
{
SqlConnection conn = new SqlConnection(sConnectionString);
conn.Open();
string query = "select * from " + TableName + "";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
DataTable ds = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ds;
}
and i am binding the table to grid view
private void LoadData()
{
clsDataAccess objDAL = new clsDataAccess();
DataTable DS = new DataTable();
string objBLL = DDLTemTableList.SelectedValue.ToString();
DS = objDAL.GetTemTableValue(objBLL);
if (DS != null && DS.Rows.Count != 0)
{
lblNoRecord.Visible = false;
foreach (DataColumn col in DS.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GVDataEntry.Columns.Add(bfield);
}
GVDataEntry.DataSource = DS;
GVDataEntry.DataBind();
GVDataEntry.Visible = true;
}
else
{
lblNoRecord.Visible = true;
GVDataEntry.DataSource = null;
GVDataEntry.DataBind();
//GVDataEntry.EmptyDataText = "No recorddata found";
}
so Table is loading to Grid View. every time when i change the tables in dropdownbox and press search button columns will change dynamically so how can i update data in Grid view through using RowEditing,RowUpdating function and i need to store the date in database?

Categories