Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > .NET для новичков > Редактирование данных в DataGrid


Автор: t77 3.8.2010, 20:21
Доброе время суток.
На сервере имеется хмл файл(News.xml)
Код

<?xml version="1.0" encoding="utf-8" ?>
<news>
    <new new_id="1">
        <title>Schumacher 'sorry' for manoeuvre</title>
        <context>
            Michael Schumacher has said he is "sorry" if Rubens Barrichello felt he had been put in danger by his blocking manoeuvre at the Hungarian Grand Prix.

            The Mercedes driver will be penalised 10 grid places at the next grand prix after he pushed his former team-mate within centimetres of a concrete wall.

            Schumacher wrote on his website: "The manoeuvre against him was too hard.

            "I didn't want to endanger him with my manoeuvre. If he had this feeling I am sorry, this was not my intention."

            Williams driver Barrichello called the move the most dangerous in his long career and said the German should have been black-flagged for dangerous driving.

            The seven-time world champion initially denied he was at fault. However, on reflection Schumacher admitted to making a mistake.
        </context>
    </new>
    <new new_id="2">
        <title>ZAGOLOVOK</title>
        <context>
            KAKOYTO KONTEKST
        </context>
    </new>
    <new new_id="3">
        <title>Wladimir - Haye is afraid</title>
        <context>
            Wladimir Klitschko has accused David Haye of being "afraid" of him and his brother.

            The British heavyweight currently holds the WBA title - the one major belt that Wladimir and his older sibling Vitali don't have in their possession.

            Haye, who defended his crown against John Ruiz earlier this year, has talked about unifying the division before he hangs up his gloves.

            He had been due to fight Wladimir last summer but a back injury forced him to pull out while talks with Vitali also stalled. Both brothers have since come out and put a 50-50 offer on the table to tempt him.

        </context>
    </new>
    <new new_id="4">
        <title>Munroe sets sights on title</title>
        <context>
            Rendall Munroe is even more confident he will become a world champion on October 24 after meeting his opponent Toshiaki Nishioka.

            The two super-bantamweight rivals got to see each other up close at the WBC Night of Champions in Cardiff at the weekend.

            Munroe will be bidding to take the WBC title from the Japanese fighter later this year when the pair go toe-to-toe at the Sumo Stadium in Tokyo.

            And after having a good look at his rival the bin man from Leicester is adamant he will be flying home from the Far East as the new champion.

        </context>
    </new>
    <new new_id="5">
        <title>Savannah the Silent Assassin</title>
        <context>
            You'll be hearing a lot about Savannah Marshall over the next two years - but you might not be hearing much from her. That's the thing about 'Silent Assassins': they hit hard but chatting's never a strong point.

            "She lets me do the talking for her," says Tim Coulter, her coach at the Headland boxing club in Hartlepool. "It's nothing personal, she's fine in the gym, it's just when she sees that pad and pen. She's spoken to journalists before and said 'just put anything down you want'." Refreshing, yes. Worrying, slightly more so. Let's hope those closest to her think the same.

            In an age when you cannot move for vacuous pronouncements from our sportsmen and women, some might think a taciturn boxer, in particular, a breath of fresh air. But the 19-year-old Marshall, who defends her European middleweight crown in Hungary next week, has a compelling story to tell and will be asked to tell it often in the lead-up to London 2012, when women's boxing will make its debut.

        </context>
    </new>
    <new new_id="6">
        <title>San Diego sign Matthews </title>
        <context>
            Ryan Matthews was excited to officially start his NFL career with the San Diego Chargers after signing a five-year rookie contract worth over $25 million.

            The Fresno State running back was a first round choice in April's draft for the Chargers, and he now starts the unenviable task of filling the boots of LaDainian Tomlinson.

            San Diego moved up the order to grab Matthews, and he looks likely to go straight into the role vacated by former league MVL Tomlinson, who was released by the team before joining the New York Jets.

            Matthews has huge shoes to fill in replacing Tomlinson, but his record of 3,280 rushing yards in three college seasons with Fresno State was enough to convince the team he is the man for the job.

            Matthews has been handed a guaranteed $15 million after signing his five-year deal, and he was thrilled to be at training camp just in time for the start of the serious pre-season work.

        </context>
    </new>
    <new new_id="7">
        <title>Judoka looks to sweep up in London </title>
        <context>
            You could say this is a "Billy Elliot" sort of tale.

            But instead of a boy having to hide his passion for ballet, here is a girl who worked hard to persuade her parents that she was a talented judoka - or judo player.

            Sarah Menezes was only nine when she first joined a judo training session at her primary school - "just for fun", as she puts it.

            Ten years later, in 2009, she won her second consecutive gold at the World Junior Championships and was named Brazil's female athlete of the year. Now, she is one of the country's best chances for a gold medal in the London 2012 Olympics.
        </context>
    </new>
    <new new_id="8">
        <title>GB pair Stevenson and Cook top taekwondo rankings </title>
        <context>
            Britain's Sarah Stevenson and Aaron Cook have become world number one in their taekwondo weight divisions.

            The pair secured gold medals at the European Championships held in Russia in May and are both hotly tipped for glory at the 2012 London Olympics.

            Olympic bronze medallist Stevenson said: "It's great to be named world number one and is a nice benchmark in my preparation for the major events."

            Both compete at September's British International Open in Manchester.

            The career of 27-year-old Stevenson is back on track having suffered 18 months of injury frustration since her bronze at the Beijing Olympics in 2008.

        </context>
    </new>
    <new new_id="9">
        <title>Javier Gomez defeats Brownlees in Hyde Park Triathlon </title>
        <context>
            Britain's Jonathan Brownlee won silver in the Hyde Park Triathlon behind Spain's Javier Gomez as brother Alistair faded in the final sprint.

            The Brownlees, buried in the pack after the cycle, clawed their way back but, on home soil, could not match Gomez.

            Gomez, who lost 2009's world title race to the elder Brownlee, set a time of one hour, 42 minutes and eight seconds.

            "This is a dream come true," Jonny told BBC Sport. Alistair was helped from the finishing line as he crossed in 10th.

            "I had nothing left, I thought I was going to come third," added the junior Brownlee.

        </context>
    </new>
    <new new_id="10">
        <title>RIM announces the BlackBerry Torch</title>
        <context>
            Research In Motion on Tuesday introduced the BlackBerry Torch, a touch-screen and sliding-keyboard device that will be the first to feature the sixth version of the company's phone software
        </context>
    </new>
</news>


Необходимо отобразить содержимое данного файла в таблице(DataGrid), следующим образом...
Первый столбик - отображает номер строки.
Второй столбик - отображает содержимое title из хмл файла
Третий столбик - отображает содержимое context из хмл файла
Четвертый столбик - отображает три кнопки(Сохранить, Редактировать, Удалить)
Каждая из трех кнопок делает соответствующее своему названию действие.
Сама таблица должна отображаться с шапкой(header), где каждый столбец будет иметь свое название...(Номер,Заголовок,Контекст,Действия)
Смотрел в интернете и нашел несколько статей по данной теме, но не совсем понимаю, что к чему. smile 
У меня получается, только отобразить данные из хмл файла в таблице, без шапки и без кнопок...
Код

protected void Page_Load(object sender, EventArgs e)
    {
        DataSet objDataSet = new DataSet();
        objDataSet.ReadXml(Server.MapPath("News.xml"));
        DataGrid1.DataSource = objDataSet.Tables[0].DefaultView;
        DataGrid1.DataBind();
    }

Помогите пожалуйста реализовать вышеописанное. 
Как это сделать?


Автор: mrbrooks 4.8.2010, 07:49
http://authors.aspalliance.com/aspxtreme/webforms/controls/addingbuttoncolumnstodatagrid.aspx

Автор: A5uKa 5.8.2010, 11:35
Ну у DataSource есть Update и Insert методы , их надо описать и в настройка DBGrid добавить соответствующие кнопки.

Автор: t77 5.8.2010, 12:56
 smile  smile 
Приведите пожалуйста небольшой пример, так чтобы было понятно.

Автор: A5uKa 5.8.2010, 13:31
Код

        [DataObjectMethod(DataObjectMethodType.Update,false)]
        static public UPD(RepGroup_ID : string, Full_name : string, GP : int, Dia : bool, Visi : bool) : void
        {
            surroundwith(connection)
            {
                MsgBox.Show
                (
                    try
                    {
                        _=SqlCommand($@"FlowClientNewUIRP
                        '$(System.Web.HttpContext.Current.User.Identity.Name)', $RepGroup_ID,
                        '$Full_name', $GP, $Dia", conn).ExecuteNonQuery(); "Параметр обновлён"
                    }
                    catch
                    {
                        | _ is SqlException => "Настройка видимости параметра не была изменена"
                        | _ => "Ошибка параметров обновления"
                    }
                )
            }
        }


Код

            <asp:ObjectDataSource ID="ODX2" runat="server" 
                    TypeName="Flow_WEB_Nemerle.SQLModule"
                    SelectMethod="RepControl" 
                    UpdateMethod="UPD" >


Ну и в гриде DataSourceID="ODX2"

Код

                    <Columns>
                        <asp:CommandField ShowEditButton="True" />


Добавлено через 6 минут и 42 секунды
п.с. но у брукса пример тоже стоит посмотреть smile

Добавлено через 7 минут и 29 секунд
п.п.с. у винграда неправильная система распознания смайлов.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)