I have a data table which already has some values, plus it is getting values from a textbox below.
Now my problem is when i dont enter a value in the textbox it still enters in the data table.
I dont want it to do that..
The code can run on any machine... any suggestions????
Thanks
public partial class WebForm6 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
// Initialize a DataTable
if (!Page.IsPostBack)
{
dt = new DataTable();
// Initialize DataColumn
DataColumn myDataColumn = new DataColumn();
//// initialize a new instance of DataColumn to add another column with different properties.
//myDataColumn = new DataColumn();
myDataColumn.ColumnName = "firstName";
// set DataType property of the column as String
myDataColumn.DataType = System.Type.GetType("System.String");
// Add and Create a Second DataColumn
dt.Columns.Add(myDataColumn);
// create a new row using NewRow() function of DataTable.
// dataRow object will inherit the schema of myDataTable to create a new row
DataRow dataRow = dt.NewRow();
dataRow["firstName"] = "John";
// add new data row to the data table.
dt.Rows.Add(dataRow);
// similarly adds the second row to the DataTable
dataRow = dt.NewRow();
dataRow["firstName"] = "Will";
dt.Rows.Add(dataRow);
Session["data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["Data"] == null)
{
dt.Columns.Add("firstName");
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
else
{
dt = (DataTable)Session["Data"];
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
} private void ClearControls()
{
txtName.Text = String.Empty;
}
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
DataRow dr;
dr = dt.NewRow();
dr["firstName"] = txtName.Text.ToString();
dt.Rows.Add(dr);
Session["Data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
and on .aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("firstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
any help....??
Change your method to be this:
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
if (!String.IsNullOrEmpty(txtname.Text))
{
DataRow dr = dt.NewRow();
dr["firstName"] = txtName.Text;
dt.Rows.Add(dr);
Session["Data"] = dt;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
Related
I want to add and delete rows dynamically in Gridview. Adding is successful. When I delete the row, the row is deleted successfully. But the data entered in other rows is cleared.
I want to delete rows. I also want to prevent the deletion of previously entered data.
Default.aspx
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ControlStyle-CssClass="row-edit" HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandName="Select" runat="server"><i class="fas fa-times"></i></asp:LinkButton>
</ItemTemplate>
<ControlStyle CssClass="row-edit"></ControlStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
Default.aspx.cs
private 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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private 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 values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
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();
}
private 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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
int indis = Gridview1.SelectedIndex;
GridViewRow satir = Gridview1.Rows[indis];
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow[] _row = dtCurrentTable.Select("RowNumber=" + satir.Cells[0].Text);
foreach (DataRow row in _row)
{
row.Delete();
}
dtCurrentTable.AcceptChanges();
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
Here's the problem
(It won't let me paste it as a flat image.)
My problem
Well, we are deleting one row at a time, right?
Ok, based on feedback, need/want this for the markup:
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Column1") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("Column2") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 4">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Column3") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete" OnClick="cmdDel_Click"
OnClientClick="return confirm('Delete this row? (cannot undo)');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
<asp:Button ID="cmdSave" runat="server" Text="Save Grid to Table" Style="margin-left:30px" OnClick="cmdSave_Click"/>
And the code looks like:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateTable();
AddRow();
LoadGrid();
ViewState["MyTable"] = dt;
}
else
{
dt = (DataTable)ViewState["MyTable"];
}
}
void CreateTable()
{
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns[0].AutoIncrementSeed = 1;
dt.Columns[0].AutoIncrementStep = 1;
dt.Columns[0].AutoIncrement = true;
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
}
void AddRow()
{
DataRow dr = dt.NewRow();
dr["Column1"] = "";
dr["Column2"] = "";
dr["Column3"] = "";
dt.Rows.Add(dr);
}
void LoadGrid()
{
// Gridview1.Columns.Clear();
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SaveData();
AddRow();
LoadGrid();
}
void SaveData()
{
// move grid changes back to table
foreach (GridViewRow gvRow in Gridview1.Rows)
{
//extract the TextBox values
DataRow dr = dt.Rows[gvRow.RowIndex];
dr["Column1"] = ((TextBox)gvRow.FindControl("TextBox1")).Text;
dr["Column2"] = ((TextBox)gvRow.FindControl("TextBox2")).Text;
dr["Column3"] = ((TextBox)gvRow.FindControl("TextBox3")).Text;
}
dt.AcceptChanges();
}
protected void cmdSave_Click(object sender, EventArgs e)
{
SaveData();
}
protected void cmdDel_Click(object sender, EventArgs e)
{
Button cmdDel = (Button)sender;
GridViewRow gvRow = (GridViewRow)cmdDel.Parent.Parent;
dt.Rows[gvRow.RowIndex].Delete();
dt.AcceptChanges();
LoadGrid();
}
Of course the save button in real use would be "submit" and move on to the next web page, or whatever task the user is working on.
And I assume this is just for learning, since a table just sitting in memory has next to zero use. I would assume that the table would be from a database, else this setup not all that much use.
I'm getting this error whenever I try to bind data inside gridview dropdownlist.
Here is the aspx code:
<asp:TemplateField HeaderText="Item Description" SortExpression="ddlItem">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind (c#):
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("lblId");
tempDataTable.Columns.Add("ddlItem");
tempDataTable.Columns.Add("txtUnit");
tempDataTable.Columns.Add("txtQty");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
gvItemList.DataSource = tempDataTable;
gvItemList.DataBind(); //Here I'm getting the error.
}
protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
Jilu1TableAdapters.tbl_ItemTableAdapter item;
item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
DataTable dt = new DataTable();
dt = item.GetItems();
ddlItem.DataSource = dt;
ddlItem.DataTextField = "Item";
ddlItem.DataValueField = "Item";
ddlItem.DataBind();
ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
DataTable dt = new DataTable();
dt = ds.GetVersion(ddlSiteID.SelectedValue);
ddlVersion.DataSource = dt;
ddlVersion.DataValueField = "Version";
ddlVersion.DataTextField = "Version";
ddlVersion.DataBind();
int ver = Convert.ToInt32(ddlVersion.Text);
DataTable dt1 = new DataTable();
dt1 = ds.GetDetails(ddlSiteID.SelectedValue, ver);
foreach (DataRow row in dt1.Rows)
{
txtSiteName.Text = (row["txtSiteName"].ToString());
ddlSiteType.Text = (row["ddlSiteType"].ToString());
txtNoBTS.Text = (row["txtNoBTS"].ToString());
txtNoLinks.Text = (row["txtNoLinks"].ToString());
txtLoadBand.Text = (row["txtLoadBand"].ToString());
ddlEBAvailability.Text = (row["ddlEBAvailability"].ToString());
txtEBPhase.Text = (row["txtEBPhase"].ToString());
txtDGCapacity.Text = (row["txtDGCapacity"].ToString());
txtDGPhase.Text = (row["txtDGPhase"].ToString());
}
gvItemList.DataSource = dt1;
gvItemList.DataBind();
}
I tried putting Text = 'Bind("ddlItem")', Datasourse, SelectedValue but still no luck.
Any help will be greatly appreciated.
In this code ,
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px"
SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
you set SelectedValue to '<%# Eval("ddlItem") %>' but ddlItem is not exist in your datasource fields .
Put the correct field which you want to display in your dropdownlist .
And I suggest you to set DataTextField and DataValueField of your DropDownList .
Set it like DataTextField="ddlItem" DataValueField="ddlItem" .
Hope it's help for you :)
Your way is wrong
try this below way
protected void gvItemList_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlItem");
//bind dropdownlist
DataTable dt = con.GetData("select * from tablename");//selected data from db or anywhere for bind ddl
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";//id
ddList.DataValueField = "YourCOLName";//displaying name
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["YourCOLName"].ToString();// default selected value
}
}
}
From my database I am retriving data table like below after making a query to DB.
I my asp.net web form application I am having GridView and it is having BoundField and DropDownList.
I want to bind LectureID to the BoundField and subjects of pariculat lecture into DropDownList.
Have no idea how to do the required binging.
LectureID SubjectName
1 Sub1
1 Sub2
1 Sub3
1 Sub4
2 Sub1
2 Sub4
<asp:GridView ID="grdvDetail" runat="server">
<Columns>
<asp:BoundField HeaderText="LectureID" DataField="LectureID" SortExpression="LectureID">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle Font-Size="11px" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlSubject" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
//Fill DataTable Using SQL Query
grdvDetail.DataSource = dt;
grdvDetail.DataBind();
for (int i = 0; i < grdvDetail.Rows.Count; i++)
{
DropDownList ddlSubject = ((DropDownList)grvProduct.Rows[i].FindControl("ddlSubject"));
DataTable dtDDL = new DataTable();
//Fill DataTable Using SQL Query
ddlSubject.DataSource = dtDDL;
ddlSubject.DataTextField = "SubjectName";
ddlSubject.DataValueField = "SubjectName";
ddlSubject.DataBind();
}
}
}
May be it is not perfect solution. Idea is to create a Key, Value collection from given datatable.
A Dictionary collection is used to keep lecture id as Key and related subjects in a List<string> as Value.
GridView is bind with Dictionary and in RowDataBound event of GridView each dropdownlist is populated as required.
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Lecture ID" />
<asp:TemplateField HeaderText="Subject Name">
<ItemTemplate>
<asp:DropDownList ID="ddlSubject" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//test data
DataTable dt = new DataTable();
dt.Columns.Add("LectureID", typeof(int));
dt.Columns.Add("SubjectName");
dt.Rows.Add(1, "Sub1");
dt.Rows.Add(1, "Sub2");
dt.Rows.Add(1, "Sub3");
dt.Rows.Add(1, "Sub4");
dt.Rows.Add(2, "Sub1");
dt.Rows.Add(2, "Sub4");
dt.AcceptChanges();
//Bind with GridView with Dictionary collection
GridView1.DataSource = GetDictionary(dt);
GridView1.DataBind();
}
}
//get a dictionary of distinct lectureID
private Dictionary<int, List<string>> GetDictionary(DataTable dt)
{
var dictionary = new Dictionary<int, List<string>>();
foreach (DataRow dr in dt.Rows)
{
int iKey = Convert.ToInt32(dr["LectureID"]);
if (dictionary.ContainsKey(iKey))
{
List<string> lst = dictionary[iKey] as List<string>;
lst.Add(dr["SubjectName"].ToString());
dictionary[iKey] = lst;
}
else
{
var lst = new List<string>();
lst.Add(dr["SubjectName"].ToString());
dictionary.Add(iKey, lst);
}
}
return dictionary;
}
Row Data Bound Event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
e.Row.DataItem != null)
{
DropDownList ddl = e.Row.FindControl("ddlSubject") as DropDownList;
ddl.DataSource = ((KeyValuePair<int, List<string>>)e.Row.DataItem).Value;
ddl.DataBind();
}
}
Result Distinct LectureID with respective Subjects in DropDownList:
I want to add a new blank row to the gridview after binding as seen in the picture when clicking the link button below. The textboxes inside the gridview should remain the same if there is any data entered in it. I just want to add one row.
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
You can run this example directly.
aspx page:
<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
<ItemTemplate>
<asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
<ItemTemplate>
<asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grd.DataSource = GetTableWithInitialData(); // get first initial data
grd.DataBind();
}
}
public DataTable GetTableWithInitialData() // this might be your sp for select
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
table.Rows.Add(1, "David", "1");
table.Rows.Add(2, "Sam", "2");
table.Rows.Add(3, "Christoff", "1.5");
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get select column header only records not required
DataRow dr;
foreach (GridViewRow gvr in grd.Rows)
{
dr = dt.NewRow();
TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
dr[0] = txtPayScale.Text;
dr[1] = txtIncrementAmount.Text;
dr[2] = txtPeriod.Text;
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add last empty row
dt.Rows.Add(dr);
grd.DataSource = dt; // bind new datatable to grid
grd.DataBind();
}
public DataTable GetTableWithNoData() // returns only structure if the select columns
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
return table;
}
protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
{
GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = " ";
gvRow.Cells.Add(tCell);
Table tbl = e.Row.Parent as Table;
tbl.Rows.Add(gvRow);
}
}
}
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:
adapter.Fill(ds);
ds.Tables(0).Rows.Add();
I am trying to place an asp gridview inside an asp datalist. For each item in the datalist I would like certain values from another database table to be returned.
I have written the following code, but the gridview returns not data (I can confirm there is records in the database and the stored procedure is correct). The asp datalist is working fine.
What am I doing wrong that is not populating the gridview?
<asp:DataList runat="server" id="listResponses" DataKeyField="QuestionID" CssClass="confirm" OnItemDataBound="listResponses_ItemDataBound">
<ItemTemplate>
<h3 class="confirm new">Question <asp:Label ID="lblaOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label></h3>
<div class="confirm_question">
<asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label>
<p class="confirm"><%# DataBinder.Eval(Container.DataItem, "QuestionText") %></p>
</div> <!-- end confirm_question -->
<asp:GridView runat="server" ID="gridResponses" DataKeyNames="QuestionID"">
<Columns>
<asp:BoundField DataField="AnswerTitle" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="Responses" HeaderText="Response Count" HeaderStyle-Width="150px" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:DataList>
And here is the code behind.
public partial class questionnaire_responses : System.Web.UI.Page
{
OsqarSQL GetData;
DataTable DT;
private string _productConnectionString;
private SqlConnection _productConn;
protected void Page_Load(object sender, EventArgs e)
{
string questionnaireId = Session["qID"].ToString();
int qid = Convert.ToInt32(questionnaireId);
GetData = new OsqarSQL();
string name = GetData.GetQuestionnaireName(qid);
lblQuestionnaireName.Text = name;
if (!IsPostBack)
{
DT = GetData.GetQuestionNameDataList(qid);
listResponses.DataSource = DT;
listResponses.DataBind();
}
}
private void BindGrid(GridView GridView, int questionId)
{
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
GridView.DataBind();
}
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses=(GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex]);
}
}
//Method from the data access class
public DataTable GetAnswerTitle(int QuestionId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetAnswer", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
,yCommand.Parameters.Add(new SqlParameter("#QUESTION_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = QuestionId;
return createDataTable(getData(myCommand));
}
You've created an empty DataTable as DataSource for your GridView.
Replace
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
with this
DataTable dt = GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;