Format GridView Auto Generated Columns - c#

I am trying to format the width of my gridview columns dynamically for easy of use in editing and updating. Is it possible to have multiple column widths defined? Here is the code I am using to create the gridview...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new table.
DataTable taskTable = new DataTable("TaskList");
// Create the columns.
taskTable.Columns.Add("Id", typeof(int));
taskTable.Columns.Add("Description", typeof(string));
taskTable.Columns.Add("IsComplete", typeof(bool));
//Add data to the new table. - could fill the table from database query if desired
for (int i = 0; i < 1; i++)
{
DataRow tableRow = taskTable.NewRow();
//tableRow["Id"] = 0;
tableRow["Description"] = "";
tableRow["IsComplete"] = false;
taskTable.Rows.Add(tableRow);
}
//Persist the table in the Session object.
Session["TaskTable"] = taskTable;
//Bind data to the GridView control.
BindData();
}
}
Is it possible to make a statement like:
taskTable.Column.Add("Id", typeof(int), width="200px");???

First you must change AutoSizeColumnsMode set to fill then you can change the width of the column.
dataGridView1.Columns[columnName].AutoSizeMode= DataGridViewAutoSizeColumnMode.None;
dataGridView1.Columns[columnName].Width = columnWidth;

Related

columns: Datagridview to Datatable

I am facing this issue, I have datagridview and a datatable.
VPfn_CreateDataGrid();//This fuction creates gridview columns
DataTable invoice_table = (DataTable)invoice_data.DataSource;
now First thing, datagridview is empty when form loads. What I am trying to do is adding data to datagridview via multiple textboxes and combomoxes and for that I am using datatable.
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
And the error is "Column 'serial_number' does not belong to table"
first you have to create a the data table with the specific column. while your datagridview is empty the DataTable also will be empty.
DataTable invoice_table = (DataTable)invoice_data.DataSource;
infront of this..
while loading your form you can create datatable with the columns.
DataTable invoice_table; //Global
private void load()
{
invoice_table = new DataTable();
invoice_table.Columns.Add("serial_number", typeof(int));
invoice_table.Columns.Add("item");
.....
}
after that
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
Try this...

change the format of DataTable, add two rows with column headers for the table

I've to add a top row in my DataTable. Then the column of top rows will be divided in two columns in the next row. After that I've to present my data in the DataTable. Currently my DataTable is showing data that is returned from the database. How can I change the format of my DataTable?
Current DataTable format
My new DataTable requirement
In this new DataTable I've to add top rows with column headers NEW & OLD. And after that, again there will be another row with new headers and from the third row there will be data. How can I get this new DataTable from the above DataTable? Note that the DataTable is generated from database.
I've just retrieve the data from the Database on click.
protected void search_Click(object sender, EventArgs e)
{
// code blocks
if (dt != null && dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
div_error.Visible = true;
DataTable_Format(dt);
}
}
You can use OnDataBound event of gridview.
protected void OnDataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "New";
cell.ColumnSpan = 4;
row.Controls.Add(cell);
cell = new TableHeaderCell();
cell.ColumnSpan = 2;
cell.Text = "Old";
row.Controls.Add(cell);
GridView1.HeaderRow.Parent.Controls.AddAt(0, row);
}

How to add row in datagridview with pre-data in c# winform?

I have a datagridview with data from SQL. I added 2 datas under each column , so if i view it in the form it would be like this..
Code is autoincremented
Code -- Date -- Total_Score
1 1/3/2015 20
2 1/3/2015 30
Now i want to add a new row..if i click the button it should add a new row with the details '3'(code is autoincremented from my database) , 1/3/2015(date should be current datetime) and the total_score cell should be empty so i could input a data. However it just shows a newly added blank row and i can't input anything on it.. here is my current code..
private void btnaddcomp_Click(object sender, EventArgs e)
{
DataTable ds = (DataTable)dgsetcompt.DataSource;
int index = this.dgsetcompt.Rows.Count;
DataRow dr = ds.NewRow();
ds.Rows.InsertAt(dr, index + 1);
dgsetcompt.DataSource = ds;
}
You should simply add data to your row in this way
private void btnaddcomp_Click(object sender, EventArgs e)
{
DataTable ds = (DataTable)dgsetcompt.DataSource;
// Create a new row...
DataRow dr = ds.NewRow();
// Set the two fields
dr["code"] = this.dgsetcompt.Rows.Count + 1;
dr["date"] = new DateTime(2015, 1, 3);
// Add the newly created row to the Rows collection of the datatable
ds.Rows.Add(dr);
// Not needed
//dgsetcompt.DataSource = ds;
}

DataTable Decrement column value after delete row

Hi. I have a DataTable one of the column is set to AutoIncrement is true. Basically I am adding some text box values to the DataTable and then binding it to the Grid View. What I am trying to achieve is if I delete a row from the grid view the row in the DataTable is also need to be deleted and also decrement the primary key column.
DataTable is declared like this private DataTable table = new DataTable(); and code is:
DataColumn promoDetailsID = new DataColumn();
promoDetailsID.ColumnName = "promoDetailsID";
promoDetailsID.DataType = System.Type.GetType("System.Int32");
promoDetailsID.AutoIncrement = true;
promoDetailsID.AutoIncrementSeed = 1;
promoDetailsID.AutoIncrementStep = 1;
table.Columns.Add(promoDetailsID);
table.Columns.Add("StartRange", typeof(string));
table.Columns.Add("EndRange", typeof(string));
table.Columns.Add("Amount", typeof(string));
table.Columns.Add("AllocationCases", typeof(string));
table.Columns.Add("AllocationUnits", typeof(string));
if (ViewState["dtTable"] != null)
{
table = (DataTable)ViewState["dtTable"];
}
table.Rows.Add(null,TxtStartRange.Text.Trim(), TxtEndRange.Text.Trim(), TxtAllocationAmount.Text.Trim(), TxtAllocationCases.Text.Trim(), TxtAllocationUnits.Text.Trim());
grdPromotions.DataSource = table;
grdPromotions.DataBind();
ViewState["dtTable"] = table;
This is the code when I am trying to delete row from grid.
protected void grdPromotions_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (ViewState["dtTable"] != null)
{
table = (DataTable)ViewState["dtTable"];
int rowIndex = Convert.ToInt32(e.RowIndex);
table.Rows[e.RowIndex].Delete();
}
table.AcceptChanges();
grdPromotions.DataSource = table;
grdPromotions.DataBind();
ViewState["dtTable"] = table;
}
There is no error I am getting but the DataTable is not updating after delete.
Since you don't use a real database it makes no sense to use DataRow.Delete which just sets it's RowState to Deleted. What you want to do is to remove the row from the DataTable.
table.Rows.RemoveAt(e.RowIndex);
If you also want to decrement the primary key column, you have to make the column writable:
table.Columns[0].ReadOnly = false;
Then you need to update the value manually:
int counter = 0;
foreach(DataRow row in table.Rows)
{
row[0] = ++counter;
}
table.Columns[0].ReadOnly = true;
Side-note: don't store a DataTable in ViewState, if you need to persist it between postbacks use the Session instead. Session lives in memory whereas ViewState will be serialized and stored in the rendered html, so it will also be transferred to the client.

Visual Web Developer Putting Drowdown Menus in Table Cells

I have created a web page that displays a table. Most of the cells of the table are already filled in but some of them require user input. I would like to put drop down menus in some of these table cells such that the cell will be populated with the selection from the menu and the drop down list will disappear.
I have gotten this to work in a single cell. However, when I tried to get it to work in a second cell everything broke. I have hacked around so much trying to find the problem that I am not even sure I remember how I got the first one working now. :-)
Here is the relevant code:
protected void Page_Load(object sender, EventArgs e)
{
// Create a DropDownList control.
DropDownList DropList = new DropDownList();
// Set the properties for the DropDownList control.
DropList.ID = "TrendList";
DropList.AutoPostBack = true;
// Manually register the event-handling method for the
// SelectedIndexChanged event.
DropList.SelectedIndexChanged += new EventHandler(this.Selection_Change);
// Because the DropDownList control is created dynamically each
// time the page is loaded, the data must be bound to the
// control each time the page is refreshed.
// Specify the data source and field names for the Text and
// Value properties of the items (ListItem objects) in the
// DropDownList control.
DropList.DataSource = CreateDataSource();
DropList.DataTextField = "ColorTextField";
DropList.DataValueField = "ColorValueField";
// Bind the data to the control.
DropList.DataBind();
// Set the default selected item when the page is first loaded.
if (!IsPostBack)
{
DropList.SelectedIndex = 0;
}
// Add the DropDownList control to the Controls collection of
// the PlaceHolder control.
p1.Controls.Add(DropList);
p2.Controls.Add(DropList);
}
ICollection CreateDataSource()
{
// Create a table to store data for the DropDownList control.
DataTable dt = new DataTable();
// Define the columns of the table.
dt.Columns.Add(new DataColumn("ColorTextField", typeof(String)));
dt.Columns.Add(new DataColumn("ColorValueField", typeof(String)));
// Populate the table with sample values.
dt.Rows.Add(CreateRow("GreenUp", "GreenUp", dt));
dt.Rows.Add(CreateRow("GreenFlat", "GreenFlat", dt));
dt.Rows.Add(CreateRow("GreenDown", "GreenDown", dt));
dt.Rows.Add(CreateRow("YellowUp", "YellowUp", dt));
dt.Rows.Add(CreateRow("YellowFlat", "YellowFlat", dt));
dt.Rows.Add(CreateRow("YellowDown", "YellowDown", dt));
dt.Rows.Add(CreateRow("RedUp", "RedUp", dt));
dt.Rows.Add(CreateRow("RedFlat", "RedFlat", dt));
dt.Rows.Add(CreateRow("RedDown", "RedDown", dt));
dt.Rows.Add(CreateRow("ClearUp", "ClearUp", dt));
dt.Rows.Add(CreateRow("ClearFlat", "ClearFlat", dt));
dt.Rows.Add(CreateRow("ClearDown", "ClearDown", dt));
// Create a DataView from the DataTable to act as the data source
// for the DropDownList control.
DataView dv = new DataView(dt);
return dv;
}
DataRow CreateRow(String Text, String Value, DataTable dt)
{
// Create a DataRow using the DataTable defined in the
// CreateDataSource method.
DataRow dr = dt.NewRow();
// This DataRow contains the ColorTextField and ColorValueField
// fields, as defined in the CreateDataSource method. Set the
// fields with the appropriate value. Remember that column 0
// is defined as ColorTextField, and column 1 is defined as
// ColorValueField.
dr[0] = Text;
dr[1] = Value;
return dr;
}
void Selection_Change(Object sender, EventArgs e)
{
// Retrieve the DropDownList control from the Controls
// collection of the PlaceHolder control.
DropDownList DropList1 = (DropDownList)p1.FindControl("TrendList");
DropDownList DropList2 = (DropDownList)p2.FindControl("TrendList");
switch (sender.ToString())
{
case "p1":
s1.InnerHtml = DropList1.SelectedItem.Value;
break;
case "p2":
s2.InnerHtml = DropList2.SelectedItem.Value;
break;
}
}
And here is the relevant snippet from the table:
<td><span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span>
<td><span id="s2" runat="server"><asp:PlaceHolder ID="p2" runat="server"></asp:PlaceHolder></span>
Now I realize that the switch control is all wrong since sender does not represent the id of the caller. But I need some way to distinguish which drop down menu is the caller so I know which HTML to replace. Also, I can only get one drop down menu to display at a time.
Any advice is appreciated.
Regards.
This code solved the problem:
public void EditTable()
{
ICollection trends = CreateDataSource();
for (int x = 1; x <= 27; x++)
{
DropDownList ddl = new DropDownList();
string index = x.ToString();
ddl.ID = "TrendList" + index;
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(this.Selection_Change);
ddl.DataSource = trends;
ddl.DataTextField = "TrendTextField";
ddl.DataValueField = "TrendValueField";
ddl.DataBind();
if (!IsPostBack)
{
ddl.SelectedIndex = 0;
}
HtmlGenericControl span = (HtmlGenericControl)form1.FindControl("s" + index);
PlaceHolder placeHolder = (PlaceHolder)span.FindControl("p" + index);
if (placeHolder != null)
{
placeHolder.Controls.Add(ddl);
}
}
}

Categories