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;
Related
This is a basic question but i didn't find appropriate answers : I have a dataset that is shown in dataGridview and it contains a column Is_Alarm of type bit (boolean) , i want to insert a Select all checkbox in that column.
I have seen many solutions but they are all about inserting a new checkbox in datagridView .
What i want is insert it after columns are shown , here's my code :
SqlDataAdapter adap= new SqlDataAdapter(select_query,con);
ds = new DataSet();
adap.Fill(ds, "Event_test");
dataGridView1.DataSource = ds.Tables[0];
I had same issue what I did might be useful for you
This is code used for gridview
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Next I Loaded data( MyTable field had id,username,email etc)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("Select * From UserInfo", con);
DataSet ds = new DataSet();
adap.Fill(ds);
con.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
For getting Ids of selected records I used few lines which is described here
http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx and modified in this way
protected void btnCheckSelected_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string ids = row.Cells[1].Text;
ListBox1.Items.Add(ids);
}
}
}
}
how to bind two columns of a database table UP and DOWN as a single column in data gridview.
Kindly help me.
.ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<span>Merged cell</span>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblMergedField" runat="server" Text='<%# Eval("ID") + " - " + Eval("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void BindData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT ID,City FROM Cities", con))
{
using (var adapter = new SqlDataAdapter(command))
{
con.Open();
var table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
con.Close();
}
}
}
}
Output:
I have created one gridview with custom column and want to perform sorting on them. When I click on column then no event is firing for sorting.
Below is the code which I have written
For .aspx page
<asp:GridView ID="grdConfigureCustomers" runat="server" AlternatingRowStyle- BackColor="Aqua" Width="1300px"
OnRowCommand="grdConfigureCustomers_RowCommand" OnRowEditing="grdConfigureCustomers_RowEditing"
OnRowUpdating="grdConfigureCustomers_RowUpdating" OnRowCancelingEdit="grdConfigureCustomers_RowCancelingEdit"
AutoGenerateColumns="false" AllowPaging="true" PageSize="5"
OnRowDeleting="grdConfigureCustomers_RowDeleting" ShowFooter="true"
onpageindexchanging="grdConfigureCustomers_PageIndexChanging" OnSorting="grdConfigureCustomers_Sorting" AllowSorting="true">
<HeaderStyle BackColor="AliceBlue" />
<Columns>
<asp:TemplateField HeaderText="Customer ID">
<ItemTemplate>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("Customer_ID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCustomerId" runat="server"></asp:TextBox><span style="color:Red;">*</span>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For .aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCustomerConfigurationGridView();
}
}
private void LoadCustomerConfigurationGridView()
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
grdConfigureCustomers.DataSource = dt;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
private void LoadCustomerConfigurationGridView(string srtexpr, string direc)
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
DataView dv = new DataView(dt);
dv.Sort = srtexpr + " " + direc;
grdConfigureCustomers.DataSource = dv;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
protected void grdConfigureCustomers_Sorting(object sender, GridViewSortEventArgs e)
{
switch (e.SortExpression)
{
case "DateLogged":
if (e.SortDirection == SortDirection.Ascending)
{
LoadCustomerConfigurationGridView("DateLogged", "ASC");
}
else
{
LoadCustomerConfigurationGridView();
}
break;
}
}
Please let me know what I missed for sorting. Thanks in advance.
You need to specify the SortExpression property in the TemplateField like this:
<asp:TemplateField HeaderText="Customer ID" SortExpression="Customer_ID">
You need to enable sorting. EnableSorting="true" in your asp.net:Gridview.
I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.
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();
}