Display gridview columns based on user selection - c#

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();
}

Related

Add a new row in bounded dataGridView on button click

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);
}
}

bind asp.net gridview column form textbox value dynamically

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 = "";
}

How to add header columns based on data fetch from the database in gridview

I have a GridView and want to make headers dynamically based on the some SQL query like...
select question from quiz where quizid is 123.
This query will return * number of questions based on the quizid.
How to create headers with the data that's been selected from database?
You can use DataTable to help with this.
I don't know which technologies you used for database management, but I used LinQ to SQL. And the following is my sample:
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();
}
And here is my aspx code:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
I will suggest you to Add HeaderText Dynamically on RowDataBound event.
You could try something like
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView.Columns[0].HeaderText = "New Header text for First Column";
}
}
You could find RowDataBound on properties >> Events of GridView control. and RowDataBound fires on binding of every row of GridView.

gridview RowUpdating index

When adding items to a gridview, I want the user to be able to select and edit/remove the item before writing the file (from the gridview entries) to a csv format. When I click on "edit" and update the information, I get an error. There is no row at position 0. (or whatever row you select to edit). Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
table = (DataTable)ViewState["table"];
ViewState["table"] = table;
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table;
//Bind data to the GridView control.
BindData();
}
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
}
public void CreateTable()
{
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
private void BindData()
{
griditems.DataSource = table;
griditems.DataBind();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
////Somewhat works, doesn't update the part field with the text entered
//TextBox partedit = (TextBox)griditems.Rows[e.RowIndex].FindControl("Part");
//DataRow row = table.NewRow();
//row["Part"] = partedit;
//row["Quantity"] = qty;
//row["Ship-To"] = shipto;
//row["Requested Date"] = reqdate;
//row["Shipping Method"] = shipmthd;
//table.Rows.Add(row);
}
The commented out part that says "Somewhat works" will write blanks in the field updated when you click update.
The time you are adding data table in Session there is no row in it, thats why you get error "There is no row at position 0."
You are assigning table from viewstate to table it would be session.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
if(Session["table"] != null)
table = (DataTable)ViewState["table"];
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table; //This adds table without any record in it.
//Bind data to the GridView control.
BindData();
}
Add data table to session after you add records in datatable.
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
Session["table"] = table;
}
Update the Session["table"] in griditems_RowUpdating after updating.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
Session["table"] = dt;
}
Note: The way you are trying to get the updating recording is not appropriate you should read more about how to access data on row updating.

How to write every time to a new row of data table?

How can i insert each time a diffrent row in datatable?
The data table is used in a dataGridView to write a log. I need each time to write in a diffrent line (row) in the datatable, when I can't know how many rows I need in runtime.
Another thing; the datatable is loaded from a XML file, so there might be already rows in the data table.
What can i do? (in short, I always write in the same row) in C#
EDIT:
here is the code:
From some reason, the DateGridView isonly having one row(This is a method that activated in a click of a button)
public void gridStart(string i, string b, string c)
{
DataTable dt = new DataTable();//empty table with no schema
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
}
You should be able to Use DataTable.NewRow(). There are several samples on that MSDN page. If you have more questions please provide some sample code to your answer.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = MyDataTable;
}
private string _fileName = "MyCache.xml";
private DataTable _myDataTable;
public DataTable MyDataTable
{
get
{
if (_myDataTable == null)
{
_myDataTable = new DataTable();
if (File.Exists(_fileName))
_myDataTable.ReadXml(_fileName);
else
InitDataTable(_myDataTable);
}
return _myDataTable;
}
}
private void InitDataTable(DataTable table)
{
table.TableName = "MyTable";
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Caller", typeof(string));
table.Columns.Add("Result", typeof(string));
}
// Have your add code call this method!
private void AddValue(DateTime date, string caller, string result)
{
var row = MyDataTable.NewRow();
row["Date"] = date;
row["Caller"] = caller;
row["Result"] = result;
MyDataTable.Rows.Add(row);
}
protected override void OnClosed(EventArgs e)
{
if (_myDataTable != null)
_myDataTable.WriteXml(_fileName, XmlWriteMode.WriteSchema);
base.OnClosed(e);
}
If it is bound to a data source, you need to first get the data source,
// Assuming it's a DataTable
DataTable dt = ((DataTable)myDataGridView.DataSource);
insert rows to your data source (like what your method is doing in your post), then tell the view to refresh its contents.
So maybe something like this would work:
public void gridStart()
{
DataTable dt = new DataTable();
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
dataGridView1.DataSource = dt;
// Call method to insert values.
}
to start up the grid, and:
public void gridInsert(string i, string b, string c)
{
DataTable dt = (DataTable)myDataGridView.DataSource;
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
// Call another method to refresh grid view.
}
to call when you want to insert data to your DataTable.
My solution:
public partial class _Default : System.Web.UI.Page
{
DataTable tb = new DataTable();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
DataTable dt = new DataTable("table");
dt.Columns.Add(new DataColumn("NR", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Dihname", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("ing", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Cost", Type.GetType("System.String")));
Session["ss"] = dt;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
tb = (DataTable)Session["ss"];
DataRow r1 = tb.NewRow();
r1[0] = ViewState["dishid"].ToString();
r1[1] = ViewState["dishname"];
r1[3] = Label3.Text;
tb.Rows.Add(r1);
DataList5.DataSource = tb;
DataList5.DataBind();
}
}

Categories

Resources