I want to bind gridview column from textbox value for example: I have two textbox and a button what i exactly want that i will give input in the two textboxes and when i clicked the button the textbox values will show in gridviw and want to do this for multiple times without replacing the previous values.
I found so many relevant answer but all are done with hard code inside button click event
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name",
typeof(string)),
new DataColumn("Age", typeof(decimal)) });
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind()
}
which replace the previous values when i insert new values, but i want to keep all the previous values in which I stuck .thanks
this code will help you to get current data from gridview to datatable
and then you can append new rows accordingly .
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt =GetGridData();
dr = dt.NewRow();
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private DataTable GetGridData ()
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
return _dataTable;
}
You can store the values from each PostBack into a Session or ViewState, otherwise you'll lose all the data when the button is clicked again.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt;
//check if the datatable already exists in the viewstate, if not create a new datatable
if (ViewState["myTable"] == null)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(decimal)) });
}
else
{
//correct viewstate exists, cast back to a datatable
dt = ViewState["myTable"] as DataTable;
}
//add the new values
dt.Rows.Add(TextBox1.Text, Convert.ToDecimal(TextBox2.Text));
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//save the datatable into the viewstate
ViewState["myTable"] = dt;
//clear the textboxes
TextBox1.Text = "";
TextBox2.Text = "";
}
Related
I have a dgv which I bind to a datatable.
public Form1()
{
da = new SqlDataAdapter("Select * from workers order by id", connStr);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
}
Here I fill the datatable and link the gridview to the datasource
private void button1_Click(object sender, EventArgs e)
{
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
When I want to add a new row to the datagridview I do the following:
private void button2_Click(object sender, EventArgs e)
{
dt.Rows.Add(dt.NewRow());
da.Update(dt); //reflects changes to database
dt.Clear();
da.Fill(dt);
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;
}
Is there a way to add the row without having to reload the whole table?
I have a datagridview and filling it using datatable as datasource .
I want to add a new row on button click , using method to first unbound it and then add new row in it . As the following :
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource= null;
dataGridView1.Rows.Add();
But instead of adding new row below the existing row , it clears the existing data in row. I think present that row as new row.
how can I add the new row below the existing row and keep the data in other rows safe .
NOTE -- columns of datagridview view are custom columns .
If you need to keep safe the existing rows, you must retain the datasource. Can try the following please?
public partial class Form1 : Form
{
DataTable dt;
public Form1()
{
InitializeComponent();
InitDataGridView();
}
private void InitDataGridView()
{
dt = new DataTable();
dt.Columns.Add("A"); dt.Columns.Add("B");
var dr = dt.NewRow();
dr["A"] = "A-init"; dr["B"] = "B-init";
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
}
private void button2_Click(object sender, EventArgs e)
{
var dr = dt.NewRow();
var counter = dt.Rows.Count;
dr["A"] = "A-" + counter; dr["B"] = "B-" + counter;
dt.Rows.Add(dr);
}
}
I am storing some column headers from an excel worksheet to a data table and extracting those column names/headers to populate my dropdown list in the aspx page. But sometimes I'm getting System.Data.DataRowView and sometimes it shows "Modified". I am using my datatable as DataSource for this Dropdownlist and the databinding is regularly failing. Can anyone help me with the code? Just a specimen so as to check where I am going wrong?
Here's the code:
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(); //Datatable data from excel file
ListItem l = new ListItem();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.DataSource = dt;
l.Text = (dt.Columns[i].ColumnName).ToString();
l.Value = (dt.Columns[i].ColumnName).ToString();
DropDownList1.DataTextField = l.Text;
DropDownList1.DataValueField = l.Value;
DropDownList1.Items.Add(l);
DropDownList1.DataBind();
}
}
}
}
You don't need to add the items to the dropdownlist if you set the datatable as datasource, as this action will do that for you. You just have to set the property that will display the desired text and the hidden value of each item. Since I don't know the structure of your Datatable, I will post a sample code of my project:
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT Id, Name FROM Projects"), cn);
da.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
This operation will already add all the items stored in the datatable into the dropdownlist
EDIT: If the DataTable structure is dynamic/unknown, you will have to add the items by using a loop such as this:
DropDownList1.Items.Clear();
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable(); //Datatable data from excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
//Now depending on whether you will have to access them by value or not:
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName)); //Without Value
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName, i)); //With a numeric value that will serve like an index
}
DropDownList1.Items.Clear();
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable(); //Datatable data from excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
//Now depending on whether you will have to access them by value or not:
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName)); //Without Value
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName, i)); //With a numeric value that will serve like an index
}
I have a Gridview and want to make header dynamically based on user selection.
How to create headers that's been selected from users.
DataTable will help you to achieve. Please follow the code below
DataClassesDataContext db = new DataClassesDataContext();
protected DataTable GetDataSource()
{
DataTable dt = new DataTable();
var questions = db.ExecuteQuery<string>("select question from quiz where quizid is 123").ToList();
// Header implementation
int count = 0;
foreach (var question in questions)
{
DataColumn dc = new DataColumn(question);
dt.Columns.Add(dc);
count++;
}
// Rows implementation here
DataRow row = dt.NewRow();
...
dt.Rows.Add(row);
return dt;
}
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}