I am trying to read XML with LINQ but I am having a problem. This is my first time using LINQ. I want to read the xml and create a datatable, then bind the datatable to gridview.
here is my xml
<?xml version="1.0" encoding="utf-8" ?>
<controls>
<control id="10001" turkce="türkçe1" english="english1" />
<control id="10002" turkce="türkçe2" english="english2" />
<control id="10003" turkce="türkçe3" english="english3" />
<control id="10004" turkce="türkçe4" english="english4" />
</controls>
here is my c# code
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Türkçe");
dt.Columns.Add("English");
//Load xml
XDocument xdoc = XDocument.Load("Language.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("control")
select new
{
id = lv1.Attribute("id").Value,
turkce = lv1.Attribute("turkce").Value,
english = lv1.Attribute("english").Value
};
foreach (var lv1 in lv1s) {
dt.Rows.Add(lv1.id,lv1.turkce,lv1.english);
}
when I run the program, it doesnt do anything. The gridview is empty. what am I doing wrong?
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Türkçe");
dt.Columns.Add("English");
//Load xml
XDocument xdoc = XDocument.Load("E:/MyApps/TestDemo/Language.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("control")
select new
{
id = lv1.Attribute("id").Value,
turkce = lv1.Attribute("turkce").Value,
english = lv1.Attribute("english").Value
};
foreach (var lv1 in lv1s)
{
dt.Rows.Add(lv1.id, lv1.turkce, lv1.english);
}
gv.DataSource = dt;
gv.DataBind();
Please note that you need to use exact URL for loading your XML file which I have done above. And also you need to bind the data table to GridView.
Below is my GridView code:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" Width="300px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server" ID="lblHeaderID" Text="ID"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server" ID="lblHeaderTürkçe" Text="Türkçe"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblTürkçe" runat="server" Text='<% #Eval("Türkçe") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server" ID="lblHeaderEnglish" Text="English"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEnglish" runat="server" Text='<% #Eval("English") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My grid view is displaying properly.
Related
I have a GridView with textBoxes inside ItemTemplates. I can retrieve the data from the column that was binded to the Gridview on page load, however, I do not see any of the manually entered text when reading the cell values.
The HTML:
<asp:GridView ID="tblRentDue" runat="server" ClientIDMode="Static">
<Columns>
<asp:BoundField DataField="Application_ID" HeaderText="Application ID" HeaderStyle-Wrap="false" />
<asp:BoundField DataField="Month" HeaderText="Month" HeaderStyle-Wrap="false" />
<asp:TemplateField HeaderText="Orignal Amount Due">
<ItemTemplate>
<asp:TextBox ID="txtOrignalAmountDue" runat="server" TextMode="Number" Text='<%# Eval("Original_Amount_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fees Due">
<ItemTemplate>
<asp:TextBox ID="txtFeesDue" runat="server" TextMode="Number" Text='<%# Eval("Fees_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount Paid">
<ItemTemplate>
<asp:TextBox ID="txtAmountPaid" runat="server" TextMode="Number" Text='<%# Eval("Amount_Paid") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Still Due">
<ItemTemplate>
<asp:TextBox ID="txtTotalStillDue" runat="server" TextMode="Number" Text='<%# Eval("Total_Still_Due") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind:
public DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
dt.Columns.Add("Month");
dt.Columns.Add("Original_Amount_Due");
dt.Columns.Add("Fees_Due");
dt.Columns.Add("Amount_Paid");
dt.Columns.Add("Total_Still_Due");
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
dr["Month"] = (row.Cells[0].Text); //These values are showing up and was loaded from the database.
dr["Original_Amount_Due"] = (row.Cells[1].Text); //Nothing showing from user input
dr["Fees_Due"] = (row.Cells[2].Text); //Nothing showing from user input
dr["Amount_Paid"] = (row.Cells[3].Text); //Nothing showing from user input
dr["Total_Still_Due"] = (row.Cells[4].Text); //Nothing showing from user input
dt.Rows.Add(dr);
}
return dt;
}
The solution I found - within the foreach loop for each textbox:
TextBox orignalAmount = (TextBox)row.Cells[1].FindControl("txtOrignalAmountDue");
dr["Original_Amount_Due"] = orignalAmount.Text;
There may be a less clunky way of doing this but it does work.
I have the following XML file:
<Employees>
<Employee>
<FirstName><a href='profile1.html'>Jon</a></FirstName>
<Age>22</Age>
</Employee>
</Employees>
what am attempting to do is have the FirstName to display as a hyperlink that directs the user to a profile page (web page).
The results from the XML file are displayed via a gridview after the user enters the first name into a text field and clicks the search button. However, the first name (search result) is currently being displayed as plain text.
The following is the code behind the search button:
XDocument document = XDocument.Load(#"C:\Users\Sammer\source\repos\MisaImports\MisaImports\data\Employee.xml");
var query = from r in document.Descendants("Employee")
where ((string)r.Element("FirstName").Value).Contains(txtSearch.Text) || ((string)r.Element("FirstName").Value).ToLower().Contains(txtSearch.Text)
select new
{
FirstName = r.Element("FirstName").Value,
//Age = r.Element("Age").Value
};
GridView1.DataSource = query;
GridView1.DataBind();
...the following depicts how I set up the gridview:
<asp:GridView ID="GridView1" runat="server"
BorderWidth="1px"
CellPadding="2"
EnableModelValidation="True"
ForeColor="white"
GridLines="None"
AutoGenerateColumns="False"
EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Keyword" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="link" runat="server" Text='<%# Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My question is, how do I get the first name to diplay as a hyperlink? Thanks in adavnce for any help rendered.
You can fetch the Url like this:-
select new
{
FirstName = r.Element("FirstName").Value,
Profile = x.Element("FirstName")?.Element("a")?.Attribute("href")?.Value ?? ""
};
Finally bind the NavigateUrl property like this:-
<asp:HyperLink ID="link" runat="server" Text='<%# Eval("FirstName") %>'
NavigateUrl='<%# Eval("profile") %>' />
I can successfully bind a DataTable to a GridView by auto generating columns, but I need to display a multi-lined cell for one of the columns. To do this, I want to use a template field with an item template using a TextBox object. I fill in the DataTable by adding columns and then adding the rows. I know my datatable is set up right because it shows all the data (except for the multi-lined cell) as I want it. My issue is getting the gridview to extract my data based on the column names and filling in the template fields I have set up. If I turn AutoGenerateColumns off then the 4 templatefield columns still appear (in the correct amount according to the datatable too), just blank, and if I have it set to true, then the 4 blank columns appear as well as 4 additional columns with the same headers that contain my data using the defaults for what the cell contains to display the information.
<asp:GridView ID="DataGrid1" runat="server" AutoGenerateColumns="False" HeaderStyle-BorderStyle="None" CellPadding="3" ItemStyle-Wrap="true" >
<Columns>
<asp:TemplateField HeaderText="Code">
<asp:ItemTemplate>
<asp:Label ID="txtCode" runat="server" Text='<%# Eval("Code") %>'>
</asp:Label>
</asp:ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<asp:ItemTemplate>
<asp:Label ID="txtTitle" runat="server" Text='<%# Eval("Title") %>'>
</asp:Label>
</asp:ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class">
<asp:ItemTemplate>
<asp:Label ID="txtClass" runat="server" Text='<%# Eval("Class") %>'>
</asp:Label>
</asp:ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="History">
<asp:ItemTemplate>
<asp:TextBox ID="txtHistory" runat="server" IsReadOnly="true" Text='<%# Eval("History")%>'>
</asp:TextBox>
</asp:ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The above is the portion of my asp.net code that relates to the GridView in question. Following is how i set up my DataTable and bind it.
DataTable table = new DataTable();
table.Columns.Add("Code", typeof(string));
table.Columns.Add("Title", typeof(string));
table.Columns.Add("Class", typeof(string));
table.Columns.Add("History", typeof(string));
for (int i = 0; i < index; i++)
{
table.Rows.Add(docs[i].Code, docs[i].Name, docs[i].Class.Name, history[i]);
}
DataGrid1.DataSource = table;
DataGrid1.DataBind();
Change .aspx code like below
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="txtCode" runat="server" Text='<%# Eval("Code") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="txtTitle" runat="server" Text='<%# Eval("Title") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class">
<ItemTemplate>
<asp:Label ID="txtClass" runat="server" Text='<%# Eval("Class") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="History">
<ItemTemplate>
<asp:TextBox ID="txtHistory" runat="server" IsReadOnly="true"
Text='<%# Eval("History")%>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
foreach (GridViewRow grdRow in grdMenuPermitted.Rows)
{
DataRow drow = dt.NewRow();
Label lblMenuName = (Label)grdRow.FindControl("lblMenuName");
HiddenField hdnID = (HiddenField)grdRow.FindControl("hdnID");
drow["MenuName"] = lblMenuName.Text;//grdRow.Cells[0].Text;
drow["MenuID"] = hdnID.Value;
//drow["lname"] = grdRow.Cells[3].Text;
dt.Rows.Add(drow);
}
This question already exists:
how to show data in gridview from arraylist in asp.net?
Closed 8 years ago.
I have a database where there is userid, problemname and status column. I am retrieving this data from database in an ArrayList and returning it. Now to show in GridView I have taken a DataTable and in the DataTable I have put three columns and I just want to show my data that is saved in the ArrayList in these columns by making one row.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id");
dt.Columns.Add("Problem Name");
dt.Columns.Add("Status");
foreach (Object row in myArrayList)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["User Id"] = ((DataRow)row)["userid"].ToString();
dt.Rows[dt.Rows.Count - 1]["Problem Name"] = ((DataRow)row) ["problemname"].ToString();
dt.Rows[dt.Rows.Count - 1]["Status"] = ((DataRow)row)["status"].ToString();
}
GridView1.DataSource =dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,problemname,status FROM problemtable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
Here is my html:
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
Why is my data is not showing in my GridView?
You need to bind your data to specific controls in your gridview. For example, you need to have labels in your gridview itemtemplate to bind your data to. Here is an example:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="cdd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id">
<ItemTemplate>
<asp:Label ID="lbl_userid" runat="server" Text='<%# Eval("User Id") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem Name">
<ItemTemplate>
<asp:Label ID="lbl_problemname" runat="server" Text='<%# Eval("Problem Name") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="status">
<ItemTemplate>
<asp:Label ID="lbl_status" runat="server" Text='<%# Eval("Status") %>' CssClass="lbl"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I agree that an ArrayList is a poor choice, but, regardless of how you're binding the data, you need to tell the gridview what it's supposed to show. You can do this using inline tags or by using an onitemdatabound trigger. I recommend you look up some more examples of gridviews.
UPDATE: THIS IS THE WORKING VERSION.
public DataSet GetObjects()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
var source = from p in CommentsList
select new { p.Img, p.Name, p.Comment };
dt.Columns.Add("Img");
dt.Columns.Add("Name");
dt.Columns.Add("Comment");
foreach (var item in source)
{
DataRow userDetailsRow=dt.NewRow();
userDetailsRow["Img"] = item.Img;
userDetailsRow["Name"] = item.Name;
DataRow comments = dt.NewRow();
userDetailsRow["Comment"] = item.Comment;
dt.Rows.Add(userDetailsRow);
//dt.Rows.Add(comments);
}
ds.Tables.Add(dt);
return ds;
}
My GridView columns section looks like this:
<Columns>
<asp:TemplateField HeaderText="#">
<HeaderStyle Width="500px" />
<ItemStyle Width="500px" Height="100px" />
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Text='<%# Bind("Comment") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="#">
<HeaderStyle Width="100px" />
<ItemStyle Width="100px" Height="100px" />
<ItemTemplate>
<asp:Image ID="imgName" runat="server" imageUrl='<%# Bind("Img") %>'></asp:Image><br />
<asp:Hyperlink ID="hyperLink" runat="server" Text='<%# Bind("Name") %>' ></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
UPDATE: The problem that I have got now is with the size of rows..that are huge and dont update with the content within,,,example: Header 33%, Row 33%, footer 33%..even though the content of the header is 10% of the gridview..how do i fix that?
You do not have a Img property. Plain and simple. This is why you have problems accessing it: it does not exist.You should create the property AND populate it.
Update
You should do this:
var source = from p in CommentsList
select new { p.Img, p.Name, p.Comment };
dt.Columns.Add("User");
dt.Columns.Add("Comment");
dt.Columns.Add("Img");
and then this:
DataRow userDetailsRow=dt.NewRow();
userDetailsRow["Img"] = item.Img;
userDetailsRow["User"] = item.Name;
Fix where it applies.
You need to add a Column in your DataTable with the name of Img before using this in DataBinding
userDetailsRow["User"] = item.Img;
should be
userDetailsRow["img"] = item.Img;